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" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
code
16028
# This file is a part of Julia. License is MIT: https://julialang.org/license function getgivens(a,b) nm = hypot(a, b) iszero(nm) && return 1, 0 return a / nm , b / nm end #Eliminate the zero eigenvalue if odd size. #Proposed in Ward, R.C., Gray L.,J., Eigensystem computation for skew-symmetric matrices and a class of symmetric matrices, 1975. @views function reducetozero(ev::AbstractVector{T}, G::AbstractVector{T}, n::Integer) where T n == 0 && return bulge = zero(T) if n > 2 #Kill last row α = ev[n-2] β = ev[n-1] γ = ev[n] c, s = getgivens(-β, γ) G[n-1] = c ; G[n] = -s; ev[n-2] *= c ev[n-1] = c * β - s * γ ev[n] = 0 bulge = -s * α #Chase the bulge for i = n-2:-2:4 α = ev[i-2] β = ev[i-1] c, s = getgivens(-β, bulge) G[i-1] = c; G[i] = -s ev[i-2] *= c ev[i-1] = c * β - s * bulge bulge = - s * α end end #Make the bulge disappear β = (n == 2 ? ev[2] : bulge) α = ev[1] c, s = getgivens(-α, β) G[1] = c; G[2] = -s ev[1] = c * α -s * β if n == 2 ev[2] = s * α + β * c end end @views function getoddvectors(Qodd::AbstractMatrix{T}, G::AbstractVector{T}, n::Integer) where T nn = div(n, 2) + 1 @inbounds( for i = 1:2:n-1 c = G[i] s = G[i+1] ii = div(i+1,2) for j = 1:nn σ = Qodd[ii, j] ω = Qodd[nn, j] Qodd[ii, j] = c * σ + s * ω Qodd[nn, j] = - s * σ + c * ω end end) end @views function eigofblock(k::Number, val::AbstractVector) val[1] = complex(0, k) val[2] = complex(0, -k) end function getshift(ev::AbstractVector{T}) where T return ev[2]^2 end @views function implicitstep_novec(ev::AbstractVector{T} , n::Integer, start::Integer) where T bulge = zero(T) shift = getshift(ev[n-1:n]) tol = T(1) * eps(T) @inbounds(for i = start:n-1 α = (i > start ? ev[i-1] : zero(ev[i])) β = ev[i] γ = ev[i+1] x1 = - α * α - β * β + shift x2 = - α * bulge + β * γ c, s = (i > start ? getgivens(α, bulge) : getgivens(x1, x2)) if i > 1 ev[i-1] = c * α + s * bulge end ev[i] = c * β - s * γ ev[i+1] = s * β + c * γ if i < n-1 ζ = ev[i+2] ev[i+2] *= c bulge = s * ζ if abs(bulge) < tol && abs(ev[i]) < tol start = i + 1 return start end end end) return start end @views function skewtrieigvals!(A::SkewHermTridiagonal{T,V,Vim}) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} n = size(A, 1) values = complex(zeros(T, n)) ev = A.ev if isodd(n) n -= 1 Ginit = similar(A, T, n) reducetozero(ev, Ginit, n) end tol = eps(T) * T(10) max_iter = 30 * n iter = 0 ; mem = T(1); count_static = 0 #mem and count_static allow to detect the failure of Wilkinson shifts. start = 1 #start remembers if a zero eigenvalue appeared in the middle of ev. while n > 2 && iter < max_iter start = implicitstep_novec(ev, n - 1, start) while n > 2 && abs(ev[n-1]) <= tol values[n] = 0 n -= 1 end while n > 2 && abs(ev[n - 2]) <= tol * abs(ev[n - 1]) eigofblock(ev[n - 1], values[n-1:n] ) n -= 2 end if start > n-2 start = 1 end if n>1 && abs(mem - ev[n-1]) < T(0.0001) * abs(ev[n-1]) count_static += 1 if count_static > 4 #Wilkinson shifts have failed, change strategy using LAPACK tridiagonal symmetric solver. values[1:n] .= complex.(0, skewtrieigvals_backup!(SkewHermTridiagonal(ev[1:n-1]))) return values end else count_static = 0 end mem = (n>1 ? ev[n-1] : T(0)) iter += 1 end if n == 2 eigofblock(ev[1], values[1:2]) return values elseif n == 1 values[1] = 0 return values elseif n == 0 return values else error("Maximum number of iterations reached, the algorithm didn't converge") end end @views function implicitstep_vec!(ev::AbstractVector{T}, Qeven::AbstractMatrix{T}, Qodd::AbstractMatrix{T}, n::Integer, N::Integer, start::Integer) where T bulge = zero(T) shift = getshift(ev[n-1:n]) tol = 10 * eps(T) @inbounds(for i = start:n-1 α = (i > start ? ev[i-1] : zero(ev[i])) β = ev[i] γ = ev[i+1] x1 = - α * α - β * β + shift x2 = - α * bulge + β * γ c, s = (i > start ? getgivens(α,bulge) : getgivens(x1, x2)) if i > 1 ev[i-1] = c * α + s * bulge end ev[i] = c * β - s * γ ev[i+1] = s * β + c * γ if i < n-1 ζ = ev[i+2] ev[i+2] *= c bulge = s * ζ if abs(bulge) < tol && abs(ev[i]) < tol start = i + 1 end end Q = (isodd(i) ? Qodd : Qeven) k = div(i+1, 2) for j = 1:N σ = Q[j, k] ω = Q[j, k+1] Q[j, k] = c*σ + s*ω Q[j, k+1] = -s*σ + c*ω end end) return start end @views function skewtrieigen_merged!(A::SkewHermTridiagonal{T}) where {T<:Real} Backup = copy(A) n = size(A, 1) values = complex(zeros(T, n)) vectors = similar(A, Complex{T}, n, n) Qodd = diagm(ones(T, div(n+1,2))) Qeven = diagm(ones(T, div(n,2))) ev = A.ev N = n if isodd(n) n -= 1 Ginit = similar(A, T, n) reducetozero(ev, Ginit, n) end tol = eps(T) * T(10) max_iter = 30 * n iter = 0 ; halfN = div(n, 2) mem = T(1); count_static = 0 #mem and count_static allow to detect the failure of Wilkinson shifts. start = 1 #start remembers if a zero eigenvalue appeared in the middle of ev. while n > 2 && iter < max_iter start = implicitstep_vec!(ev, Qeven, Qodd, n - 1, halfN, start) while n > 2 && abs(ev[n-1]) <= tol values[n] = 0 n -= 1 end while n > 2 && abs(ev[n - 2]) <= tol * abs(ev[n - 1]) eigofblock(ev[n - 1], values[n-1:n] ) n -= 2 end if start > n-2 start = 1 end if n>1 && abs(mem - ev[n-1]) < T(0.0001) * abs(ev[n-1]) count_static += 1 if count_static > 4 #Wilkinson shifts have failed, change strategy using LAPACK tridiagonal symmetric solver. values, Q = skewtrieigen_backup!(Backup) return Eigen(values, Q) end else count_static = 0 end mem = (n>1 ? ev[n-1] : T(0)) iter += 1 end if n > 0 if n == 2 eigofblock(ev[1], values[1:2]) else values[1] = 0 end if isodd(N) getoddvectors(Qodd, Ginit, N - 1) end s2 = T(1/sqrt(2)) zero = T(0) i = 1 countzeros = 0 @inbounds(while i <= N ii = div(i+1,2) if iszero(values[i]) if iseven(countzeros) for j = 1:2:N-1 jj = div(j+1, 2) vectors[j, i] = complex(Qodd[jj, ii], zero) end if isodd(N) vectors[N, i] = complex(Qodd[halfN+1, ii],zero) end else for j = 1:2:N-1 jj = div(j+1, 2) vectors[j+1, i] = complex(Qeven[jj, ii], zero) end end countzeros +=1 i += 1 else if isodd(countzeros) for j = 1:2:N-1 jj = div(j+1, 2) vectors[j, i] = complex(zero, -s2 * Qodd[jj, ii+1]) vectors[j+1, i] = complex(s2 * Qeven[jj, ii], zero) vectors[j, i+1] = complex(-s2 * Qodd[jj, ii+1], zero) vectors[j+1, i+1] = complex(zero, s2 * Qeven[jj,ii]) end if isodd(N) vectors[N, i] = complex(zero, -s2 * Qodd[halfN+1, ii+1]) vectors[N, i+1] = complex(-s2 * Qodd[halfN+1, ii+1], zero) end else for j = 1:2:N-1 jj = div(j+1, 2) vectors[j, i] = complex(s2 * Qodd[jj, ii], zero) vectors[j+1, i] = complex(zero, - s2 * Qeven[jj, ii]) vectors[j, i+1] = complex(zero,s2 * Qodd[jj, ii]) vectors[j+1, i+1] = complex(- s2 * Qeven[jj,ii], zero) end if isodd(N) vectors[N, i] = complex(s2 * Qodd[halfN+1, ii],zero) vectors[N, i+1] = complex(zero, s2 * Qodd[halfN+1, ii]) end end i+=2 end end) if isodd(N) @inbounds(for j = 1: 2: N jj = div(j+1,2) vectors[j, N] = complex(Qodd[jj, halfN+1], zero) end) end return Eigen(values, vectors) elseif n == 0 return Eigen(values, complex.(Qodd)) else error("Maximum number of iterations reached, the algorithm didn't converge") end end @views function skewtrieigen_divided!(A::SkewHermTridiagonal{T}) where {T<:Real} Backup = copy(A) n = size(A, 1) values = complex(zeros(T, n)) vectorsreal = similar(A, n, n) vectorsim = similar(A, n, n) Qodd = diagm(ones(T, div(n+1,2))) Qeven = diagm(ones(T, div(n,2))) ev = A.ev N = n if isodd(n) n -= 1 Ginit = similar(A, T, n) reducetozero(ev, Ginit, n) end tol = eps(T)*T(10) max_iter = 30 * n iter = 0 ; halfN = div(n, 2) mem = T(1); count_static = 0 #mem and count_static allow to detect the failure of Wilkinson shifts. start = 1 #start remembers if a zero eigenvalue appeared in the middle of ev. while n > 2 && iter < max_iter start = implicitstep_vec!(ev, Qeven, Qodd, n - 1, halfN, start) while n > 2 && abs(ev[n-1]) <= tol values[n] = 0 n -= 1 end while n > 2 && abs(ev[n - 2]) <= tol * abs(ev[n - 1]) eigofblock(ev[n - 1], values[n-1:n] ) n -= 2 end if n > 2 && abs(ev[n-1]-mem) < tol eigofblock(ev[n - 1], values[n-1:n] ) n -= 2 end if start > n-2 start = 1 end if n>1 && abs(mem - ev[n-1]) < T(0.0001) * abs(ev[n-1]) count_static += 1 if count_static > 4 #Wilkinson shifts have failed, change strategy using LAPACK tridiagonal symmetric solver. Q = complex.(vectorsreal, vectorsim) values, Q = skewtrieigen_backup!(Backup) vectorsreal .= real.(Q) vectorsim .= imag.(Q) return values, vectorsreal, vectorsim end else count_static = 0 end mem = (n>1 ? ev[n-1] : T(0)) iter += 1 end if n > 0 if n == 2 eigofblock(ev[1], values[1:2]) else values[1] = 0 end if isodd(N) getoddvectors(Qodd, Ginit, N - 1) end s2 = T(1/sqrt(2)) NN = div(N+1, 2) i = 1 countzeros = 0 @inbounds(while i <= N ii = div(i+1,2) if iszero(values[i]) if iseven(countzeros) for j = 1:2:N-1 jj = div(j+1, 2) vectorsreal[j, i] = Qodd[jj, ii] end if isodd(N) vectorsreal[N, i] = Qodd[halfN+1, ii] end else for j = 1:2:N-1 jj = div(j+1, 2) vectorsreal[j+1, i] = Qeven[jj, ii] end end countzeros +=1 i += 1 else if isodd(countzeros) for j = 1:2:N-1 jj = div(j+1, 2) vectorsim[j, i] = -s2 * Qodd[jj, ii+1] vectorsreal[j+1, i] = s2 * Qeven[jj, ii] vectorsreal[j, i+1] = -s2 * Qodd[jj, ii+1] vectorsim[j+1, i+1] = s2 * Qeven[jj,ii] end if isodd(N) vectorsreal[N, i] = -s2 * Qodd[halfN+1, ii+1] vectorsim[N, i+1] = -s2 * Qodd[halfN+1, ii+1] end else for j = 1:2:N-1 jj = div(j+1, 2) vectorsreal[j, i] = s2 * Qodd[jj, ii] vectorsim[j+1, i] = - s2 * Qeven[jj, ii] vectorsim[j, i+1] = s2 * Qodd[jj, ii] vectorsreal[j+1, i+1] = - s2 * Qeven[jj,ii] end if isodd(N) vectorsreal[N, i] = s2 * Qodd[halfN+1, ii] vectorsim[N, i+1] = s2 * Qodd[halfN+1, ii] end end i+=2 end end) if isodd(N) @inbounds(for j = 1:2:N jj = div(j+1,2) vectorsreal[j,N] = Qodd[jj, halfN+1] end) end return values, vectorsreal, vectorsim elseif n == 0 return values, vectorsreal, vectorsim else error("Maximum number of iterations reached, the algorithm didn't converge") end end #The Wilkinson shifts have some pathological cases. #In these cases, the skew-symmetric eigenvalue problem is solved as detailed in #C. Penke, A. Marek, C. Vorwerk, C. Draxl, P. Benner, High Performance Solution of Skew-symmetric Eigenvalue Problems with Applications in Solving the Bethe-Salpeter Eigenvalue Problem, Parallel Computing, Volume 96, 2020. @views function skewtrieigvals_backup!(S::SkewHermTridiagonal{T,V,Vim}) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} n = size(S,1) H = SymTridiagonal(zeros(eltype(S.ev), n), copy(S.ev)) vals = eigvals!(H) return vals .= .-vals end @views function skewtrieigen_backup!(S::SkewHermTridiagonal{T,V,Vim}) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} n = size(S, 1) H = SymTridiagonal(zeros(T, n), S.ev) trisol = eigen!(H) vals = complex.(0, -trisol.values) Qdiag = complex(zeros(T,n,n)) c = 1 @inbounds for j=1:n c = 1 @simd for i=1:2:n-1 Qdiag[i,j] = trisol.vectors[i,j] * c Qdiag[i+1,j] = complex(0, trisol.vectors[i+1,j] * c) c *= (-1) end end if n % 2 == 1 Qdiag[n,:] = trisol.vectors[n,:] * c end return vals, Qdiag end
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
code
9549
# This file is a part of Julia. License is MIT: https://julialang.org/license struct SkewHermitian{T<:Number,S<:AbstractMatrix{<:T}} <: AbstractMatrix{T} data::S function SkewHermitian{T,S}(data) where {T,S<:AbstractMatrix{<:T}} LA.require_one_based_indexing(data) new{T,S}(data) end end """ SkewHermitian(A) <: AbstractMatrix Construct a `SkewHermitian` view of the skew-Hermitian matrix `A` (`A == -A'`), which allows one to exploit efficient operations for eigenvalues, exponentiation, and more. Takes "ownership" of the matrix `A`. See also [`skewhermitian`](@ref), which takes the skew-hermitian part of `A`, and [`skewhermitian!`](@ref), which does this in-place, along with [`isskewhermitian`](@ref) which checks whether `A == -A'`. """ function SkewHermitian(A::AbstractMatrix) isskewhermitian(A) || throw(ArgumentError("matrix `A` must be skew-Hermitian (equal `-A')")) return SkewHermitian{eltype(A),typeof(A)}(A) end SkewHermitian(A::SkewHermitian) = A """ skewhermitian(A) Returns the skew-Hermitian part of A, i.e. `(A-A')/2`. See also [`skewhermitian!`](@ref), which does this in-place. """ skewhermitian(A::AbstractMatrix) = skewhermitian!(copyto!(similar(A, typeof(zero(eltype(A))/2)), A)) skewhermitian(a::Number) = imag(a) Base.@propagate_inbounds Base.getindex(A::SkewHermitian, i::Integer, j::Integer) = A.data[i,j] Base.@propagate_inbounds function Base.setindex!(A::SkewHermitian, v, i::Integer, j::Integer) if i == j real(v) == 0 || throw(ArgumentError("diagonal elements must be zero")) else A.data[i,j] = v A.data[j,i] = -v' end return v end Base.similar(A::SkewHermitian, ::Type{T}) where {T} = SkewHermitian(similar(parent(A), T) .= 0) Base.similar(A::SkewHermitian) = SkewHermitian(similar(parent(A)) .= 0) # see https://github.com/JuliaLang/julia/pull/24163: Base.similar(A::SkewHermitian, ::Type{T}, dims::Dims{N}) where {T,N} = similar(parent(A), T, dims) # Conversion Base.Matrix(A::SkewHermitian) = Matrix(A.data) Base.Array(A::SkewHermitian) = Matrix(A) Base.parent(A::SkewHermitian) = A.data SkewHermitian{T,S}(A::SkewHermitian{T,S}) where {T,S} = A SkewHermitian{T,S}(A::SkewHermitian) where {T,S<:AbstractMatrix{T}} = SkewHermitian{T,S}(S(A.data)) Base.AbstractMatrix{T}(A::SkewHermitian) where {T} = SkewHermitian(AbstractMatrix{T}(A.data)) Base.copy(A::SkewHermitian) = SkewHermitian(copy(A.data)) function Base.copyto!(dest::SkewHermitian, src::SkewHermitian) copyto!(dest.data, src.data) return dest end function Base.copyto!(dest::SkewHermitian, src::AbstractMatrix) isskewhermitian(src) || throw(ArgumentError("can only copy skew-Hermitian data to SkewHermitian")) copyto!(dest.data, src) return dest end Base.copyto!(dest::AbstractMatrix, src::SkewHermitian) = copyto!(dest, src.data) Base.size(A::SkewHermitian,n) = size(A.data,n) Base.size(A::SkewHermitian) = size(A.data) """ isskewhermitian(A) Returns whether `A` is skew-Hermitian, i.e. whether `A == -A'`. """ function isskewhermitian(A::AbstractMatrix{<:Number}) axes(A,1) == axes(A,2) || throw(ArgumentError("axes $(axes(A,1)) and $(axes(A,2)) do not match")) @inbounds for i in axes(A,1) for j = firstindex(A, 1):i A[i,j] == -A[j,i]' || return false end end return true end isskewhermitian(A::SkewHermitian) = true isskewhermitian(a::Number) = a == -a' """ isskewsymmetric(A) Returns whether `A` is skew-symmetric, i.e. whether `A == -transpose(A)`. """ function isskewsymmetric(A::AbstractMatrix{<:Number}) axes(A,1) == axes(A,2) || throw(ArgumentError("axes $(axes(A,1)) and $(axes(A,2)) do not match")) @inbounds for i in axes(A,1) for j = firstindex(A, 1):i A[i,j] == -A[j,i] || return false end end return true end isskewsymmetric(A::SkewHermitian{<:Real}) = true isskewsymmetric(a::Number) = iszero(a) """ skewhermitian!(A) Transforms `A` in-place to its skew-Hermitian part `(A-A')/2`, and returns a [`SkewHermitian`](@ref) view. """ function skewhermitian!(A::AbstractMatrix{T}) where {T<:Number} LA.require_one_based_indexing(A) n = LA.checksquare(A) two = T(2) @inbounds for i in 1:n A[i,i] = T isa Real ? zero(T) : complex(zero(real(T)),imag(A[i,i])) for j = 1:i-1 a = (A[i,j] - A[j,i]')/two A[i,j] = a A[j,i] = -a' end end return SkewHermitian(A) end LA.Tridiagonal(A::SkewHermitian) = Tridiagonal(A.data) Base.isreal(A::SkewHermitian) = isreal(A.data) Base.transpose(A::SkewHermitian) = SkewHermitian(transpose(A.data)) Base.adjoint(A::SkewHermitian) = SkewHermitian(A.data') Base.real(A::SkewHermitian{<:Real}) = A Base.real(A::SkewHermitian) = SkewHermitian(real(A.data)) Base.imag(A::SkewHermitian) = LA.Hermitian(imag(A.data)) Base.conj(A::SkewHermitian) = SkewHermitian(conj(A.data)) Base.conj!(A::SkewHermitian) = SkewHermitian(conj!(A.data)) LA.tr(A::SkewHermitian{<:Real}) = zero(eltype(A)) LA.tr(A::SkewHermitian) = tr(A.data) LA.tril!(A::SkewHermitian) = tril!(A.data) LA.tril(A::SkewHermitian) = tril!(copy(A)) LA.triu!(A::SkewHermitian) = triu!(A.data) LA.triu(A::SkewHermitian) = triu!(copy(A)) LA.tril!(A::SkewHermitian,k::Integer) = tril!(A.data,k) LA.tril(A::SkewHermitian,k::Integer) = tril!(copy(A),k) LA.triu!(A::SkewHermitian,k::Integer) = triu!(A.data,k) LA.triu(A::SkewHermitian,k::Integer) = triu!(copy(A),k) function LA.dot(A::SkewHermitian, B::SkewHermitian) n = size(A, 2) T = eltype(A) two = T(2) if n != size(B, 2) throw(DimensionMismatch("A has size $(size(A)) but B has size $(size(B))")) end dotprod = zero(dot(first(A), first(B))) @inbounds for j = 1:n for i = 1:j-1 dotprod += two * dot(A.data[i, j], B.data[i, j]) end dotprod += dot(A.data[j, j], B.data[j, j]) end return dotprod end Base.:-(A::SkewHermitian) = SkewHermitian(-A.data) for f in (:+, :-) @eval begin Base.$f(A::SkewHermitian, B::SkewHermitian) = SkewHermitian($f(A.data, B.data)) end end ## Matvec LA.mul!(y::StridedVecOrMat, A::SkewHermitian, x::StridedVecOrMat, α::Number, β::Number) = LA.mul!(y, A.data, x, α, β) LA.mul!(y::StridedVecOrMat, A::SkewHermitian, x::StridedVecOrMat) = LA.mul!(y, A.data, x) LA.mul!(y::StridedVecOrMat, A::SkewHermitian, B::SkewHermitian, α::Number, β::Number) = LA.mul!(y, A.data, B.data, α, β) LA.mul!(y::StridedVecOrMat, A::SkewHermitian, B::SkewHermitian) = LA.mul!(y, A.data, B.data) LA.mul!(y::StridedVecOrMat, A::StridedMatrix, B::SkewHermitian, α::Number, β::Number) = LA.mul!(y, A, B.data, α, β) LA.mul!(y::StridedVecOrMat, A::StridedMatrix, B::SkewHermitian) = LA.mul!(y, A, B.data) function LA.dot(x::AbstractVector, A::SkewHermitian, y::AbstractVector) LA.require_one_based_indexing(x, y) (length(x) == length(y) == size(A, 1)) || throw(DimensionMismatch()) r = zero(eltype(x)) * zero(eltype(A)) * zero(eltype(y)) @inbounds for j = 1:length(y) r += dot(x[j], A.data[j,j], y[j]) # zero if A is real @simd for i = 1:j-1 Aij = A.data[i,j] r += dot(x[i], Aij, y[j]) + dot(x[j], -Aij', y[i]) end end return r end # Scaling: for op in (:*, :/, :\) if op in (:*, :/) @eval Base.$op(A::SkewHermitian, x::Number) = $op(A.data, x) @eval Base.$op(A::SkewHermitian, x::Real) = SkewHermitian($op(A.data, x)) end if op in (:*, :\) @eval Base.$op(x::Number, A::SkewHermitian) = $op(x, A.data) @eval Base.$op(x::Real, A::SkewHermitian) = SkewHermitian($op(x, A.data)) end end function checkreal(x::Number) isreal(x) || throw(ArgumentError("in-place scaling of SkewHermitian requires a real scalar")) return real(x) end LA.rdiv!(A::SkewHermitian, b::Number) = rdiv!(A.data, checkreal(b)) LA.ldiv!(b::Number, A::SkewHermitian) = ldiv!(checkreal(b), A.data) LA.rmul!(A::SkewHermitian, b::Number) = rmul!(A.data, checkreal(b)) LA.lmul!(b::Number, A::SkewHermitian) = lmul!(checkreal(b), A.data) for f in (:det, :logdet, :lu, :lu!, :lq, :lq!, :qr, :qr!) @eval LA.$f(A::SkewHermitian) = LA.$f(A.data) end @eval LA.inv(A::SkewHermitian) = skewhermitian!(LA.inv(A.data)) LA.kron(A::SkewHermitian,B::StridedMatrix) = kron(A.data,B) LA.kron(A::StridedMatrix,B::SkewHermitian) = kron(A,B.data) @views function LA.schur!(A::SkewHermitian{<:Real}) F = eigen!(A) return Schur(typeof(F.vectors)(Diagonal(F.values)), F.vectors, F.values) end LA.schur(A::SkewHermitian{<:Real})= LA.schur!(copyeigtype(A)) # special Diagonal rules, similar to those for HermOrSym in LinearAlgebra's diagonal.jl, # since we can't assume diagonal * skewhermitian is skewhermitian (unless it is real diagonal) Base.:*(A::SkewHermitian, D::Diagonal) = mul!(similar(A, Base.promote_op(*, eltype(A), eltype(D.diag)), size(A)), A, D) Base.:*(D::Diagonal, A::SkewHermitian) = mul!(similar(A, Base.promote_op(*, eltype(A), eltype(D.diag)), size(A)), D, A) if isdefined(LinearAlgebra, :_rdiv!) # JuliaLang/julia#42343 (julia ≈ 1.9) Base.:/(A::SkewHermitian, D::Diagonal) = LinearAlgebra._rdiv!(similar(A, Base.promote_op(/, eltype(A), eltype(D.diag)), size(A)), A, D) else Base.:/(A::SkewHermitian, D::Diagonal) = rdiv!(copyto!(similar(A, Base.promote_op(/, eltype(A), eltype(D.diag)), size(A)), A), D) end Base.:\(D::Diagonal, B::SkewHermitian) = ldiv!(similar(B, Base.promote_op(\, eltype(D.diag), eltype(B)), size(B)), D, B)
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
code
21604
# This file is a part of Julia. License is MIT: https://julialang.org/license #### Specialized matrix types #### struct SkewHermTridiagonal{T, V<:AbstractVector{T}, Vim<:Union{AbstractVector{<:Real},Nothing}} <: AbstractMatrix{T} ev::V # subdiagonal dvim::Vim # diagonal imaginary parts (may be nothing if T is real) function SkewHermTridiagonal{T, V, Vim}(ev, dvim) where {T, V<:AbstractVector{T}, Vim} LA.require_one_based_indexing(ev) if Vim !== Nothing LA.require_one_based_indexing(dvim) eltype(dvim) === real(T) || throw(ArgumentError("mismatch between $(real(T)) and $(eltype(dvim))")) end new{T, V, Vim}(ev, dvim) end end """ SkewHermTridiagonal(ev::V, dvim::Vim) where {V <: AbstractVector, Vim <: AbstractVector{<:Real}} Construct a skewhermitian tridiagonal matrix from the subdiagonal (`ev`) and the imaginary part of the main diagonal (`dvim`). The result is of type `SkewHermTridiagonal` and provides efficient specialized eigensolvers, but may be converted into a regular matrix with `convert(Array, _)` (or `Array(_)` for short). # Examples ```jldoctest julia> ev = complex.([7, 8, 9] , [7, 8, 9]) 3-element Vector{Complex{Int64}}: 7 + 7im 8 + 8im 9 + 9im julia> dvim = [1, 2, 3, 4] 4-element Vector{Int64}: 1 2 3 4 julia> SkewHermTridiagonal(ev, dvim) 4×4 SkewHermTridiagonal{Complex{Int64}, Vector{Complex{Int64}}, Vector{Int64}}: 0+1im -7+7im 0+0im 0+0im 7-7im 0+2im -8+8im 0+0im 0+0im -8+8im 0+3im -9+9im 0+0im 0+0im 9+9im 0+4im ``` """ SkewHermTridiagonal(ev::AbstractVector{T}, dvim::Nothing=nothing) where {T<:Real} = SkewHermTridiagonal{T, typeof(ev), Nothing}(ev, nothing) SkewHermTridiagonal{T}(ev::AbstractVector, dvim::Nothing=nothing) where {T<:Real} = SkewHermTridiagonal(convert(AbstractVector{T}, ev)::AbstractVector{T}) # complex skew-hermitian case SkewHermTridiagonal(ev::AbstractVector{Complex{T}}, dvim::Nothing=nothing) where T = SkewHermTridiagonal{Complex{T}, typeof(ev), Nothing}(ev, nothing) SkewHermTridiagonal(ev::AbstractVector{Complex{T}}, dvim::AbstractVector{T}) where T = SkewHermTridiagonal{Complex{T}, typeof(ev), typeof(dvim)}(ev, dvim) SkewHermTridiagonal{Complex{T}}(ev::AbstractVector, dvim::AbstractVector) where T = SkewHermTridiagonal(convert(AbstractVector{Complex{T}}, ev)::AbstractVector{Complex{T}}, convert(AbstractVector{T}, dvim)::AbstractVector{T}) """ SkewHermTridiagonal(A::AbstractMatrix) Construct a skewhermitian tridiagonal matrix from first subdiagonal and main diagonal of the skewhermitian matrix `A`. # Examples ```jldoctest julia> A = [1 2 3; 2 4 5; 3 5 6] 3×3 Matrix{Int64}: 1 2 3 2 4 5 3 5 6 julia> SkewHermTridiagonal(A) 3×3 SkewHermTridiagonal{Int64, Vector{Int64}}: 0 -2 0 2 0 -5 0 5 0 ``` """ function SkewHermTridiagonal(A::AbstractMatrix) if iszero(real(diag(A))) && !iszero(imag(diag(A))) if diag(A, 1) == - adjoint.(diag(A, -1)) SkewHermTridiagonal(diag(A, -1),imag(diag(A))) else throw(ArgumentError("matrix is not skew-hermitian; cannot convert to SkewHermTridiagonal")) end else if diag(A, 1) == - adjoint.(diag(A, -1)) SkewHermTridiagonal(diag(A, -1)) else throw(ArgumentError("matrix is not skew-hermitian; cannot convert to SkewHermTridiagonal")) end end end SkewHermTridiagonal{T,V,Vim}(S::SkewHermTridiagonal{T,V,Vim}) where {T,V<:AbstractVector{T}, Vim<:Union{AbstractVector{<:Real},Nothing}} = S SkewHermTridiagonal{T,V,Vim}(S::SkewHermTridiagonal) where {T,V<:AbstractVector{T}, Vim<:Union{AbstractVector{<:Real},Nothing}} = SkewHermTridiagonal(convert(V, S.ev)::V,convert(Vim, S.dvim)::Vim) SkewHermTridiagonal{T}(S::SkewHermTridiagonal{T}) where {T} = S SkewHermTridiagonal{T}(S::SkewHermTridiagonal) where {T} = SkewHermTridiagonal(convert(AbstractVector{T}, S.ev)::AbstractVector{T},convert(AbstractVector{<:Real}, S.dvim)::AbstractVector{<:Real}) SkewHermTridiagonal(S::SkewHermTridiagonal) = S function SkewHermTridiagonal(A::SkewHermitian{T}) where T n = size(A, 1) sub = similar(A, n - 1) if T<:Real for i=1:n-1 sub[i] = A.data[i+1,i] end return SkewHermTridiagonal(sub) else d = similar(A, real(T), n) for i=1:n-1 d[i] = imag(A[i,i]) sub[i] = A[i+1,i] end d[n] = imag(A[n,n]) if iszero(d) return SkewHermTridiagonal(sub) else return SkewHermTridiagonal(sub, d) end end end function Base.AbstractMatrix{T}(S::SkewHermTridiagonal) where {T} if S.dvim !== nothing SkewHermTridiagonal(convert(AbstractVector{T}, S.ev)::AbstractVector{T},convert(AbstractVector{<:real(T)}, S.dvim)::AbstractVector{<:real(T)}) else SkewHermTridiagonal(convert(AbstractVector{T}, S.ev)::AbstractVector{T}) end end function Base.Matrix{T}(M::SkewHermTridiagonal) where T n = size(M, 1) Mf = zeros(T, n, n) n == 0 && return Mf if M.dvim !== nothing @inbounds for i = 1:n-1 Mf[i,i] = complex(0, M.dvim[i]) Mf[i+1,i] = M.ev[i] Mf[i,i+1] = -M.ev[i]' end Mf[n,n] = complex(0, M.dvim[n]) else @inbounds for i = 1:n-1 Mf[i+1,i] = M.ev[i] Mf[i,i+1] = -M.ev[i]' end end return Mf end Base.Matrix(M::SkewHermTridiagonal{T}) where {T} = Matrix{promote_type(T, typeof(zero(T)))}(M) Base.Array(M::SkewHermTridiagonal) = Matrix(M) Base.size(A::SkewHermTridiagonal) = (length(A.ev) + 1,length(A.ev) + 1) function Base.size(A::SkewHermTridiagonal, d::Integer) if d < 1 throw(ArgumentError("dimension must be ≥ 1, got $d")) elseif d<=2 return length(A.ev) + 1 else return 1 end end function Base.similar(S::SkewHermTridiagonal{<:Complex{T}}, ::Type{Complex{T}}) where {T} if S.dvim !== nothing return SkewHermTridiagonal(similar(S.ev, Complex{T}), similar(S.dvim,T)) else return SkewHermTridiagonal(similar(S.ev, Complex{T})) end end Base.similar(S::SkewHermTridiagonal{<:Real}, ::Type{T}) where {T<:Real} = SkewHermTridiagonal(similar(S.ev, T)) Base.similar(S::SkewHermTridiagonal, ::Type{T}, dims::Union{Dims{1},Dims{2}}) where {T} = zeros(T, dims...) function Base.copyto!(dest::SkewHermTridiagonal, src::SkewHermTridiagonal) (copyto!(dest.ev, src.ev);dest) if src.dvim !== nothing (copyto!(dest.dvim, src.dvim) ; dest) end end function LA.Tridiagonal(A::SkewHermTridiagonal) if A.dvim !== nothing return Tridiagonal(A.ev,complex.(0, A.dvim),.-conj.(A.ev)) else return Tridiagonal(A.ev,zeros(eltype(A.ev), length(A.ev) + 1),.-conj.(A.ev)) end end #Elementary operations Base.conj(M::SkewHermTridiagonal{<:Real}) = SkewHermTridiagonal(conj.(M.ev)) Base.conj(M::SkewHermTridiagonal{<:Complex}) = SkewHermTridiagonal(conj.(M.ev),(M.dvim !==nothing ? -M.dvim : nothing)) Base.copy(M::SkewHermTridiagonal{<:Real}) = SkewHermTridiagonal(copy(M.ev)) Base.copy(M::SkewHermTridiagonal{<:Complex}) = SkewHermTridiagonal(copy(M.ev), (M.dvim !==nothing ? copy(M.dvim) : nothing)) function Base.imag(M::SkewHermTridiagonal{T}) where T if M.dvim !== nothing LA.SymTridiagonal(M.dvim, imag.(M.ev)) else n=size(M,1) LA.SymTridiagonal(zeros(real(T), n), imag.(M.ev)) end end Base.real(M::SkewHermTridiagonal) = SkewHermTridiagonal(real.(M.ev)) Base.transpose(S::SkewHermTridiagonal) = -S Base.adjoint(S::SkewHermTridiagonal{<:Real}) = -S Base.adjoint(S::SkewHermTridiagonal) = -S function LA.tr(S::SkewHermTridiagonal{T}) where T if T<:Real || S.dvim === nothing return zero(eltype(S.ev)) else return complex(zero(eltype(S.dvim)), sum(S.dvim)) end end Base.copy(S::LA.Adjoint{<:Any,<:SkewHermTridiagonal}) = SkewHermTridiagonal(map(x -> copy.(adjoint.(x)), (S.parent.ev,S.parent.dvim))...) isskewhermitian(S::SkewHermTridiagonal) = true @views function LA.rdiv!(A::SkewHermTridiagonal, b::Number) rdiv!(A.ev, checkreal(b)) if A.dvim !== nothing rdiv!(A.dvim, checkreal(b)) end return A end @views function LA.ldiv!(b::Number,A::SkewHermTridiagonal) ldiv!(checkreal(b), A.ev) if A.dvim !== nothing ldiv!(checkreal(b), A.dvim) end return A end @views function LA.rmul!(A::SkewHermTridiagonal, b::Number) rmul!(A.ev, checkreal(b)) if A.dvim !== nothing rmul!(A.dvim, checkreal(b)) end return A end @views function LA.lmul!(b::Number,A::SkewHermTridiagonal) lmul!(checkreal(b), A.ev) if A.dvim !== nothing lmul!(checkreal(b), A.dvim) end return A end @views function LA.rdiv!(A::SkewHermTridiagonal, B::AbstractMatrix) return Tridiagonal(A) / B end @views function LA.ldiv!(B::AbstractVecOrMat,A::SkewHermTridiagonal) return B / Tridiagonal(A) end @views function LA.rmul!(A::SkewHermTridiagonal, b::StridedVecOrMat) y = similar(A, size(A,1), size(b,2)) return mul!(y,Tridiagonal(A),b) end @views function LA.lmul!(b::StridedVecOrMat,A::SkewHermTridiagonal) y = similar(A, size(b,1), size(A,2)) return mul!(y, b, Tridiagonal(A)) end Base.:*(A::SkewHermTridiagonal, B::Number) = rmul!(copy(A), B) Base.:*(B::Number,A::SkewHermTridiagonal) = lmul!(B, copy(A)) Base.:/(A::SkewHermTridiagonal, B::Number) = rdiv!(copy(A), B) Base.:\(B::Number, A::SkewHermTridiagonal) = ldiv!(B, copy(A)) Base.:*(A::SkewHermTridiagonal, B::StridedVecOrMat) = rmul!(A, B) Base.:*(B::StridedVecOrMat, A::SkewHermTridiagonal) = lmul!(B, A) Base.:/(A::SkewHermTridiagonal, B::StridedMatrix) = rdiv!(A, B) Base.:/(B::AbstractVecOrMat, A::SkewHermTridiagonal) = B / Tridiagonal(A) Base.:\(B::StridedVecOrMat, A::SkewHermTridiagonal) = ldiv!(B, A) Base.:\(A::SkewHermTridiagonal, B::AbstractVecOrMat) = Tridiagonal(A) \ B function Base.:*(A::SkewHermTridiagonal, B::T) where {T<:Complex} if A.dvim !== nothing return Tridiagonal(A.ev * B, complex.(0, A.dvim)* B, .-conj.(A.ev) .* B) else return Tridiagonal(A.ev * B, zeros(eltype(A.ev), size(A, 1)), .-conj.(A.ev) .* B) end end function Base.:*(B::T,A::SkewHermTridiagonal) where {T<:Complex} if A.dvim !== nothing return Tridiagonal(B * A.ev, B * complex.(0, A.dvim) , .-B .* conj.(A.ev)) else return Tridiagonal(B * A.ev, zeros(eltype(A.ev), size(A, 1)), .-B .* conj.(A.ev)) end end function Base.:/(A::SkewHermTridiagonal, B::T) where {T<:Complex} if A.dvim !== nothing return Tridiagonal(A.ev / B, complex.(0, A.dvim)/ B, .-conj.(A.ev) ./ B) else return Tridiagonal(A.ev / B, zeros(eltype(A.ev), size(A, 1)), .-conj.(A.ev) ./ B) end end function Base.:\(B::T,A::SkewHermTridiagonal) where {T<:Complex} if A.dvim !== nothing return Tridiagonal(B \ A.ev, B \ complex.(0, A.dvim), .-B .\ conj.(A.ev)) else return Tridiagonal(B \ A.ev, zeros(eltype(A.ev), size(A, 1)), .-B .\ conj.(A.ev)) end end function Base. ==(A::SkewHermTridiagonal, B::SkewHermTridiagonal) if A.dvim !== nothing && B.dvim!== nothing return (A.ev==B.ev) &&(A.dvim==B.dvim) elseif A.dvim === nothing && B.dvim === nothing return (A.ev==B.ev) else return false end end function Base.:+(A::SkewHermTridiagonal, B::SkewHermTridiagonal) if A.dvim !== nothing && B.dvim !== nothing return SkewHermTridiagonal(A.ev + B.ev, A.dvim + B.dvim) elseif A.dvim === nothing && B.dvim !== nothing return SkewHermTridiagonal(A.ev + B.ev, B.dvim) elseif B.dvim === nothing && A.dvim !== nothing return SkewHermTridiagonal(A.ev + B.ev, A.dvim) else return SkewHermTridiagonal(A.ev + B.ev) end end function Base.:-(A::SkewHermTridiagonal, B::SkewHermTridiagonal) if A.dvim !== nothing && B.dvim !== nothing return SkewHermTridiagonal(A.ev - B.ev, A.dvim - B.dvim) elseif A.dvim === nothing && B.dvim !== nothing return SkewHermTridiagonal(A.ev - B.ev, -B.dvim) elseif B.dvim === nothing && A.dvim !== nothing return SkewHermTridiagonal(A.ev - B.ev,A.dvim) else return SkewHermTridiagonal(A.ev - B.ev) end end function Base.:-(A::SkewHermTridiagonal) if A.dvim !== nothing return SkewHermTridiagonal(-A.ev, -A.dvim) else return SkewHermTridiagonal(-A.ev) end end @inline LA.mul!(A::StridedVecOrMat, B::SkewHermTridiagonal, C::StridedVecOrMat, alpha::Number, beta::Number) = _mul!(A, B, C, LA.MulAddMul(alpha, beta)) @inline function _mul!(C::StridedVecOrMat, S::SkewHermTridiagonal, B::StridedVecOrMat, _add::LA.MulAddMul) m, n = size(B, 1), size(B, 2) if !(m == size(S, 1) == size(C, 1)) throw(DimensionMismatch("A has first dimension $(size(S,1)), B has $(size(B,1)), C has $(size(C,1)) but all must match")) end if n != size(C, 2) throw(DimensionMismatch("second dimension of B, $n, doesn't match second dimension of C, $(size(C,2))")) end if m == 0 return C elseif iszero(_add.alpha) return LA._rmul_or_fill!(C, _add.beta) end α = S.dvim β = S.ev if α === nothing @inbounds begin for j = 1:n x₊ = B[1, j] x₀ = zero(x₊) # If m == 1 then β[1] is out of bounds β₀ = m > 1 ? zero(β[1]) : zero(eltype(β)) for i = 1:m - 1 x₋, x₀, x₊ = x₀, x₊, B[i + 1, j] β₋, β₀ = β₀, β[i] LA._modify!(_add, β₋*x₋ - adjoint(β₀) * x₊, C, (i, j)) end LA._modify!(_add, β₀ * x₀ , C, (m, j)) end end else @inbounds begin for j = 1:n x₊ = B[1, j] x₀ = zero(x₊) # If m == 1 then β[1] is out of bounds β₀ = m > 1 ? zero(β[1]) : zero(eltype(β)) for i = 1:m - 1 x₋, x₀, x₊ = x₀, x₊, B[i + 1, j] β₋, β₀ = β₀, β[i] LA._modify!(_add, β₋*x₋ +α[i]*x₀*1im -adjoint(β₀)*x₊, C, (i, j)) end LA._modify!(_add, β₀*x₀+α[m]*x₊*1im , C, (m, j)) end end end return C end function LA.dot(x::AbstractVector, S::SkewHermTridiagonal, y::AbstractVector) LA.require_one_based_indexing(x, y) nx, ny = length(x), length(y) (nx == size(S, 1) == ny) || throw(DimensionMismatch()) if iszero(nx) return dot(zero(eltype(x)), zero(eltype(S)), zero(eltype(y))) end dv = S.dvim ev = S.ev x₀ = x[1] x₊ = (nx > 1 ? x[2] : zero(x[1])) sub = (nx > 1 ? ev[1] : zero(x[1])) if dv !== nothing r = dot( adjoint(sub)*x₊+complex(zero(dv[1]),-dv[1])*x₀, y[1]) @inbounds for j in 2:nx-1 x₋, x₀, x₊ = x₀, x₊, x[j+1] sup, sub = -adjoint(sub), ev[j] r += dot(adjoint(sup)*x₋+complex(zero(dv[j]),-dv[j])*x₀ + adjoint(sub)*x₊, y[j]) end r += dot(-sub*x₀+complex(zero(dv[nx]),-dv[nx])*x₊, y[nx]) else r = dot( adjoint(sub)*x₊, y[1]) @inbounds for j in 2 : nx-1 x₋, x₀, x₊ = x₀, x₊, x[j+1] sup, sub = -adjoint(sub), ev[j] r += dot(adjoint(sup)*x₋ + adjoint(sub)*x₊, y[j]) end r += dot(adjoint(-adjoint(sub))*x₀, y[nx]) end return r end @views function LA.eigvals!(A::SkewHermTridiagonal{T,V,Vim}, sortby::Union{Function,Nothing}=nothing) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} vals = imag.(skewtrieigvals!(A)) !isnothing(sortby) && sort!(vals, by=sortby) return complex.(0, vals) end @views function LA.eigvals!(A::SkewHermTridiagonal{T,V,Vim}, irange::UnitRange) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} vals = skewtrieigvals!(A,irange) return complex.(0, vals) end @views function LA.eigvals!(A::SkewHermTridiagonal{T,V,Vim}, vl::Real,vh::Real) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} vals = skewtrieigvals!(A,-vh,-vl) return complex.(0, vals) end @views function LA.eigvals!(A::SkewHermTridiagonal{T,V,Vim}, sortby::Union{Function,Nothing}=nothing) where {T<:Complex,V<:AbstractVector{T},Vim<:Union{AbstractVector{<:Real},Nothing}} S = to_symtridiagonal(A)[1] vals = eigvals!(S) !isnothing(sortby) && sort!(vals, by=sortby) reverse!(vals) return complex.(0, -vals) end @views function LA.eigvals!(A::SkewHermTridiagonal{T,V,Vim}, irange::UnitRange) where {T<:Complex,V<:AbstractVector{T},Vim<:Union{AbstractVector{<:Real},Nothing}} n = size(A,1) S = to_symtridiagonal(A)[1] irange2 = .-(irange.- n) vals = eigvals!(S, irange2) return complex.(0, -vals) end @views function LA.eigvals!(A::SkewHermTridiagonal{T,V,Vim}, vl::Real,vh::Real) where {T<:Complex,V<:AbstractVector{T},Vim<:Union{AbstractVector{<:Real},Nothing}} S = to_symtridiagonal(A)[1] vals = eigvals!(S, -vh , -vl) return complex.(0, vals) end LA.eigvals(A::SkewHermTridiagonal{T,V,Vim}, sortby::Union{Function,Nothing}=nothing) where {T,V,Vim} = LA.eigvals!(copyeigtype(A),sortby) LA.eigvals(A::SkewHermTridiagonal{T,V,Vim}, irange::UnitRange) where {T,V,Vim} = LA.eigvals!(copyeigtype(A), irange) LA.eigvals(A::SkewHermTridiagonal{T,V,Vim}, vl::Real,vh::Real) where {T,V,Vim}= LA.eigvals!(copyeigtype(A), vl,vh) @views function skewtrieigvals!(S::SkewHermTridiagonal{T,V,Vim},irange::UnitRange) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} n = size(S,1) H = SymTridiagonal(zeros(eltype(S.ev), n), S.ev) vals = eigvals!(H, irange) return vals .= .-vals end @views function skewtrieigvals!(S::SkewHermTridiagonal{T,V,Vim},vl::Real,vh::Real) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing} n = size(S, 1) H = SymTridiagonal(zeros(eltype(S.ev), n), S.ev) vals = eigvals!(H,vl,vh) return vals .= .-vals end LA.eigen!(A::SkewHermTridiagonal{T,V,Vim}) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing}= skewtrieigen_merged!(A) @views function LA.eigen!(A::SkewHermTridiagonal{T,V,Vim}) where {T<:Complex,V<:AbstractVector{T},Vim<:Union{AbstractVector{<:Real},Nothing}} n = size(A, 1) S, Q = to_symtridiagonal(A) Eig = eigen!(S) Vec = similar(A.ev, n, n) mul!(Vec, Q, Eig.vectors) return Eigen(Eig.values.*(-1im),Vec) end function copyeigtype(A::SkewHermTridiagonal) B = similar(A , LA.eigtype( eltype(A.ev) )) copyto!(B, A) return B end LA.eigen(A::SkewHermTridiagonal) = LA.eigen!(copyeigtype(A)) LA.eigvecs(A::SkewHermTridiagonal) = eigen(A).vectors @views function LA.svdvals!(A::SkewHermTridiagonal) vals = imag.(eigvals!(A)) vals .= abs.(vals) return sort!(real(vals); rev=true) end LA.svdvals(A::SkewHermTridiagonal{T,V,Vim}) where {T<:Real,V<:AbstractVector{T},Vim<:Nothing}=svdvals!(copyeigtype(A)) @views function LA.svd!(A::SkewHermTridiagonal) n = size(A, 1) E = eigen!(A) U = E.vectors vals = imag.(E.values) I = sortperm(vals; by = abs, rev = true) permute!(vals, I) Base.permutecols!!(U, I) V2 = U .* -1im @inbounds for i=1:n if vals[i] < 0 vals[i] = -vals[i] @simd for j=1:n V2[j,i] = -V2[j,i] end end end return LA.SVD(U, vals, adjoint(V2)) end LA.svd(A::SkewHermTridiagonal) = svd!(copyeigtype(A)) @views function to_symtridiagonal(A::SkewHermTridiagonal{T}) where {T<:Complex} n = size(A, 1) V = similar(A.ev, n - 1) Q = similar(A.ev, n) Q[1] = 1 V .= A.ev V.*= 1im for i=1:n-2 nm = abs(V[i]) Q[i+1] = V[i] / nm V[i] = nm V[i+1] *= Q[i+1] end if n > 1 nm = abs(V[n-1]) Q[n] = V[n-1] / nm V[n-1] = nm end if A.dvim !== nothing SymTri = SymTridiagonal(-A.dvim, real(V)) else SymTri = SymTridiagonal(zeros(real(T), n), real(V)) end return SymTri, Diagonal(Q) end ################### # Generic methods # ################### # det with optional diagonal shift for use with shifted Hessenberg factorizations #det(A::SkewHermTridiagonal; shift::Number=false) = det_usmani(A.ev, A.dv, A.ev, shift) #logabsdet(A::SkewHermTridiagonal; shift::Number=false) = logabsdet(ldlt(A; shift=shift)) # show a "⋅" for structural zeros when printing function Base.replace_in_print_matrix(A::SkewHermTridiagonal, i::Integer, j::Integer, s::AbstractString) i==j-1 || i==j+1 || (A.dvim !== nothing && i==j) ? s : Base.replace_with_centered_mark(s) end Base.@propagate_inbounds function Base.getindex(A::SkewHermTridiagonal{T}, i::Integer, j::Integer) where T @boundscheck checkbounds(A, i, j) if i == j + 1 return @inbounds A.ev[j] elseif i + 1 == j return @inbounds -A.ev[i]' elseif T <: Complex && i == j && A.dvim!==nothing return complex(zero(real(T)), A.dvim[i]) else return zero(T) end end @inline function Base.setindex!(A::SkewHermTridiagonal, x, i::Integer, j::Integer) @boundscheck checkbounds(A, i, j) if i == j+1 @inbounds A.ev[j] = x elseif i == j-1 @inbounds A.ev[i] = -x' elseif T <: Complex && i == j && isreal(x) @inbounds A.dvim[i]== x elseif T <: Complex && i == j && imag(x)!=0 @inbounds A.dvim[i]== imag(x) else throw(ArgumentError("cannot set off-diagonal entry ($i, $j)")) end return x end
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
code
25366
using LinearAlgebra, Random, SparseArrays using SkewLinearAlgebra using Test Random.seed!(314159) # use same pseudorandom stream for every test isapproxskewhermitian(A) = A ≈ -A' @testset "README.md" begin # test from the README examples A = [0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0] @test isskewhermitian(A) A = SkewHermitian(A) @test tr(A) == 0 @test det(A) ≈ 81 @test isskewhermitian(inv(A)) @test inv(A) ≈ [0 1 -3 -8; -1 0 4 7; 3 -4 0 2; 8 -7 -2 0]/9 @test A \ [1,2,3,4] ≈ [-13,13,1,-4]/3 v = [8.306623862918073, 8.53382018538718, -1.083472677771923] @test hessenberg(A).H ≈ Tridiagonal(v,[0,0,0,0.],-v) iλ₁,iλ₂ = 11.93445871397423, 0.7541188264752862 l = imag.(eigvals(A)) sort!(l) @test l ≈ sort!([iλ₁,iλ₂,-iλ₂,-iλ₁]) @test Matrix(hessenberg(A).Q) ≈ [1.0 0.0 0.0 0.0; 0.0 -0.2407717061715382 -0.9592700375676934 -0.14774972261267352; 0.0 0.8427009716003843 -0.2821382463434394 0.4585336219014009; 0.0 -0.48154341234307674 -0.014106912317171805 0.8763086996337883] @test eigvals(A, 0,15) ≈ [iλ₁,iλ₂]*im @test eigvals(A, 1:3) ≈ [iλ₁,iλ₂,-iλ₂]*im @test svdvals(A) ≈ [iλ₁,iλ₁,iλ₂,iλ₂] C = skewchol(A) @test transpose(C.R)*C.J*C.R≈A[C.p,C.p] end @testset "SkewLinearAlgebra.jl" begin for T in (Int32,Float32,Float64,ComplexF32), n in [1, 2, 10, 11] if T<:Integer A = skewhermitian!(rand(convert(Array{T},-10:10), n, n) * T(2)) else A = skewhermitian!(randn(T, n, n)) end @test eltype(A) === T @test isskewhermitian(A) @test isskewhermitian(A.data) B = T(2) * Matrix(A) @test isskewhermitian(B) s = rand(T) @test skewhermitian(s) == imag(s) @test parent(A) == A.data @test similar(A) == SkewHermitian(zeros(T, n, n)) @test similar(A,ComplexF64) == SkewHermitian(zeros(ComplexF64, n, n)) @test A == copy(A)::SkewHermitian @test A === SkewHermitian(A) # issue #126 @test copyto!(copy(4 * A), A) == A @test size(A) == size(A.data) @test size(A, 1) == size(A.data, 1) @test size(A, 2) == size(A.data, 2) @test Array(A) == A.data @test tr(A) == tr(A.data) @test tril(A) == tril(A.data) @test tril(A, 1) == tril(A.data, 1) @test triu(A) == triu(A.data) @test triu(A,1) == triu(A.data, 1) @test (-A).data == -(A.data) A2 = A.data * A.data @test A * A == A2 ≈ Hermitian(A2) @test A * B == A.data * B @test B * A == B * A.data if iseven(n) # for odd n, a skew-Hermitian matrix is singular @test inv(A)::SkewHermitian ≈ inv(A.data) end @test (A * 2).data == A.data * T(2) @test (2 * A).data == T(2) * A.data @test (A / 2).data == A.data / T(2) C = A + A @test C.data == A.data + A.data B = SkewHermitian(B) C = A - B @test C.data == -A.data B = triu(A) @test B ≈ triu(A.data) B = tril(A, n - 2) @test B ≈ tril(A.data, n - 2) k = dot(A, A) @test k ≈ dot(A.data, A.data) if n > 1 @test A[2,1] == A.data[2,1] A[n, n-1] = 3 @test A[n, n-1] === T(3) @test A[n-1, n] === T(-3) end x = rand(T, n) y = zeros(T, n) mul!(y, A, x, T(2), T(0)) @test y == T(2) * A.data * x mul!(y, A, x) @test y == A * x k = dot(y, A, x) @test k ≈ adjoint(y) * A.data * x k = copy(y) mul!(y, A, x, T(2), T(3)) @test y ≈ T(2) * A * x + T(3) * k B = copy(A) copyto!(B, A) @test B == A B = Matrix(A) @test B == A.data C = similar(B, n, n) mul!(C, A, B, T(2), T(0)) @test C == T(2) * A.data * B mul!(C, B, A, T(2), T(0)) @test C == T(2) * B * A.data B = SkewHermitian(B) mul!(C, B, A, T(2), T(0)) @test C == T(2) * B.data * A.data B = Matrix(A) @test kron(A, B) ≈ kron(A.data, B) A.data[n,n] = T(4) @test isskewhermitian(A.data) == false A.data[n,n] = T(0) A.data[n,1] = T(4) @test isskewhermitian(A.data) == false LU = lu(A) @test LU.L * LU.U ≈ A.data[LU.p,:] if !(T<:Integer) LQ = lq(A) @test LQ.L * LQ.Q ≈ A.data end QR = qr(A) @test QR.Q * QR.R ≈ A.data if T<:Integer A = skewhermitian(rand(T,n,n) * 2) else A = skewhermitian(randn(T,n,n)) end if eltype(A)<:Real F = schur(A) @test A.data ≈ F.vectors * F.Schur * F.vectors' end for f in (real, imag) @test f(A) == f(Matrix(A)) end end # issue #98 @test skewhermitian([1 2; 3 4]) == [0.0 -0.5; 0.5 0.0] # issue #126 let D = Diagonal([1.0+0im]), S = SkewHermitian(fill(0+1.234im, 1,1)) @test D * S == S * D == D \ S == S / D end end @testset "hessenberg.jl" begin for T in (Int32,Float32,Float64,ComplexF32), n in [1, 2, 10, 11] if T<:Integer A = skewhermitian(rand(T(-10):T(10), n, n) * T(2)) else A = skewhermitian(randn(T, n, n)) end B = Matrix(A) HA = hessenberg(A) HB = hessenberg(B) @test Matrix(HA.H) ≈ Matrix(HB.H) @test Matrix(HA.Q) ≈ Matrix(HB.Q) end for T in (Int32,Float64,ComplexF32) A = zeros(T, 4, 4) A[2:4,1] = ones(T,3) A[1,2:4] = -ones(T,3) A = SkewHermitian(A) B = Matrix(A) HA = hessenberg(A) HB = hessenberg(B) @test Matrix(HA.H) ≈ Matrix(HB.H) end end @testset "eigen.jl" begin for T in (Int32,Float32,Float64,ComplexF32), n in [1, 2, 10, 11] if T<:Integer A = skewhermitian(rand(convert(Array{T},-10:10),n,n)* T(2)) else A = skewhermitian(randn(T, n, n)) end B = Matrix(A) valA = imag(eigvals(A)) valB = imag(eigvals(B)) sort!(valA) sort!(valB) @test valA ≈ valB Eig = eigen(A) valA = Eig.values Q2 = Eig.vectors valB,Q = eigen(B) @test Q2*diagm(valA)*adjoint(Q2) ≈ A.data valA = imag(valA) valB = imag(valB) sort!(valA) sort!(valB) @test valA ≈ valB Svd = svd(A) @test Svd.U * Diagonal(Svd.S) * Svd.Vt ≈ A.data @test svdvals(A) ≈ svdvals(B) end end @testset "exp.jl" begin for T in (Int32,Float32,Float64,ComplexF32), n in [1, 2, 10, 11] if T<:Integer A = skewhermitian(rand(convert(Array{T},-10:10), n, n)*T(2)) else A = skewhermitian(randn(T, n, n)) end B = Matrix(A) @test exp(B) ≈ exp(A) @test cis(A) ≈ Hermitian(exp(B*1im)) @test Hermitian(cos(B)) ≈ cos(A) @test skewhermitian!(sin(B)) ≈ sin(A) sc = sincos(A) @test sc[1]≈ skewhermitian!(sin(B)) @test sc[2]≈ Hermitian(cos(B)) @test skewhermitian!(sinh(B)) ≈ sinh(A) @test Hermitian(cosh(B)) ≈ cosh(A) if T<:Complex || iseven(n) @test exp(log(A)) ≈ A end if issuccess(lu(cos(B), check = false)) && issuccess(lu(det(exp(2A)+I), check = false)) if isapproxskewhermitian(tan(B)) && isapproxskewhermitian(tanh(B)) @test tan(B) ≈ tan(A) @test tanh(B) ≈ tanh(A) end end if issuccess(lu(sin(B), check = false)) && issuccess(lu(det(exp(2A)-I), check = false)) try if isapproxskewhermitian(cot(B)) && isapproxskewhermitian(coth(B)) @test cot(B) ≈ cot(A) @test coth(B) ≈ coth(A) end catch end end end for T in (Int32 ,Float32,Float64,ComplexF32), n in [2, 10, 11] if T<:Integer A = SkewHermTridiagonal(rand(convert(Array{T},-20:20), n - 1) * T(2)) else if T<:Complex A = SkewHermTridiagonal(rand(T, n - 1), rand(real(T), n)) else A = SkewHermTridiagonal(rand(T, n - 1)) end end B = Matrix(A) @test exp(B) ≈ exp(A) @test cis(A) ≈ Hermitian(exp(B*1im)) @test Hermitian(cos(B)) ≈ cos(A) @test skewhermitian!(sin(B)) ≈ sin(A) sc = sincos(A) @test sc[1]≈ skewhermitian!(sin(B)) @test sc[2]≈ Hermitian(cos(B)) @test skewhermitian!(sinh(B)) ≈ sinh(A) @test Hermitian(cosh(B)) ≈ cosh(A) if T<:Complex || iseven(n) @test exp(log(A)) ≈ A end if issuccess(lu(cos(B), check = false)) && issuccess(lu(det(exp(2A)+I), check = false)) if isapproxskewhermitian(tan(B)) && isapproxskewhermitian(tanh(B)) @test tan(B) ≈ tan(A) @test tanh(B) ≈ tanh(A) end end if issuccess(lu(sin(B), check = false)) && issuccess(lu(det(exp(2A)-I), check = false)) try if isapproxskewhermitian(cot(B)) && isapproxskewhermitian(coth(B)) @test cot(B) ≈ cot(A) @test coth(B) ≈ coth(A) end catch end end end end @testset "tridiag.jl" begin for T in (Int32,Float32,Float64,ComplexF32), n in [1, 2, 10, 11] if T<:Integer C = skewhermitian(rand(convert(Array{T},-20:20), n, n) * T(2)) else C = skewhermitian(randn(T,n,n)) end A = SkewHermTridiagonal(C) @test isskewhermitian(A) == true @test Tridiagonal(A) ≈ Tridiagonal(C) if T<:Integer A = SkewHermTridiagonal(rand(convert(Array{T},-20:20), n - 1) * T(2)) C = rand(convert(Array{T},-10:10), n, n) D1 = rand(convert(Array{T},-10:10), n, n) x = rand(convert(Array{T},-10:10), n) y = rand(convert(Array{T},-10:10), n) else if T<:Complex A = SkewHermTridiagonal(rand(T, n - 1), rand(real(T), n)) else A = SkewHermTridiagonal(rand(T, n - 1)) end C = randn(T, n, n) D1 = randn(T, n, n) x = randn(T, n) y = randn(T, n) end D2 = copy(D1) B = Matrix(A) mul!(D1, A, C, T(2), T(1)) @test D1 ≈ D2 + T(2) * Matrix(A) * C mul!(D1, A, C, T(2), T(0)) @test size(A) == (n, n) @test size(A,1) == n if A.dvim !== nothing @test conj(A) == SkewHermTridiagonal(conj.(A.ev),-A.dvim) @test copy(A) == SkewHermTridiagonal(copy(A.ev),copy(A.dvim)) else @test conj(A) == SkewHermTridiagonal(conj.(A.ev)) @test copy(A) ==SkewHermTridiagonal(copy(A.ev)) end @test real(A) == SkewHermTridiagonal(real.(A.ev)) @test transpose(A) == -A @test Matrix(adjoint(A)) == adjoint(Matrix(A)) @test Array(A) == Matrix(A) @test D1 ≈ T(2) * Matrix(A) * C @test Matrix(A + A) == Matrix( 2 * A) @test Matrix(A)/2 == Matrix(A / 2) @test Matrix(A + A) == Matrix(A * 2) @test Matrix(A- 2 * A) == Matrix(-A) if n>1 @test dot(x, A, y) ≈ dot(x, Matrix(A), y) end if T<:Complex z = rand(T) @test A * z ≈ Tridiagonal(A) * z @test z * A ≈ z * Tridiagonal(A) @test A / z ≈ Tridiagonal(A) / z @test z \ A ≈ z \ Tridiagonal(A) end B = Matrix(A) @test tr(A) ≈ tr(B) @test B == copy(A) == A yb = rand(T, 1, n) if !iszero(det(Tridiagonal(A))) @test A \ x ≈ B \ x @test yb / A ≈ yb / B #@test A / B ≈ B / A ≈ I end @test A * x ≈ B * x @test yb * A ≈ yb * B @test B * A ≈ A * B ≈ B * B @test size(A,1) == n EA = eigen(A) EB = eigen(B) Q = EA.vectors @test eigvecs(A) ≈ Q @test Q * diagm(EA.values) * adjoint(Q) ≈ B valA = imag(EA.values) valB = imag(EB.values) sort!(valA) sort!(valB) @test valA ≈ valB Svd = svd(A) @test Svd.U * Diagonal(Svd.S) * Svd.Vt ≈ B @test svdvals(A) ≈ svdvals(B) for f in (real, imag) @test Matrix(f(A)) == f(B) end if n > 1 A[2,1] = 2 @test A[2,1] === T(2) === -A[1,2]' end end B = SkewHermTridiagonal([3,4,5]) @test B == [0 -3 0 0; 3 0 -4 0; 0 4 0 -5; 0 0 5 0] @test repr("text/plain", B) == "4×4 SkewHermTridiagonal{$Int, Vector{$Int}, Nothing}:\n ⋅ -3 ⋅ ⋅\n 3 ⋅ -4 ⋅\n ⋅ 4 ⋅ -5\n ⋅ ⋅ 5 ⋅" C = SkewHermTridiagonal(complex.([3,4,5]), [6,7,8,9]) @test C == [6im -3 0 0; 3 7im -4 0; 0 4 8im -5; 0 0 5 9im] @test repr("text/plain", C) == "4×4 SkewHermTridiagonal{Complex{$Int}, Vector{Complex{$Int}}, Vector{$Int}}:\n 0+6im -3+0im ⋅ ⋅ \n 3+0im 0+7im -4+0im ⋅ \n ⋅ 4+0im 0+8im -5+0im\n ⋅ ⋅ 5+0im 0+9im" end @testset "pfaffian.jl" begin # real skew-hermitian matrices for n in [1, 2, 3, 10, 11] A = skewhermitian(rand(-10:10,n,n) * 2) Abig = BigInt.(A.data) @test pfaffian(A) ≈ pfaffian(Abig) == pfaffian(SkewHermitian(Abig)) if VERSION ≥ v"1.7" # for exact det of BigInt matrices @test pfaffian(Abig)^2 == det(Abig) end @test Float64(pfaffian(Abig)^2) ≈ (iseven(n) ? det(Float64.(A)) : 0.0) logpf, sign = logabspfaffian(A) @test pfaffian(A) ≈ sign * exp(logpf) S = SkewHermTridiagonal(A) logpf, sign = logabspfaffian(S) @test pfaffian(S) ≈ sign * exp(logpf) ≈ sign * sqrt(det(Matrix(S))) end # complex skew-symmetric matrices # n=11 is a bit jinxed because of https://github.com/JuliaLang/julia/issues/54287 for n in [1, 2, 3, 10, 20] A = rand((-10:10) .+ 1im * (-10:10)', n, n) A = (A .- transpose(A)) ./ 2 Abig = Complex{Rational{BigInt}}.(A) @test pfaffian(A) ≈ SkewLinearAlgebra.exactpfaffian(Abig) @test pfaffian(A)^2 ≈ det(A) atol=√eps(Float64) * max(1, abs(det(A))) if VERSION ≥ v"1.7" # for exact det of BigInt matrices @test SkewLinearAlgebra.exactpfaffian(Abig)^2 == det(Abig) end logpf, sign = logabspfaffian(A) @test pfaffian(A) ≈ sign * exp(logpf) end # issue #49 @test pfaffian(big.([0 14 7 -10 0 10 0 -11; -14 0 -10 7 13 -9 -12 -13; -7 10 0 -4 6 -17 -1 18; 10 -7 4 0 -2 -4 0 11; 0 -13 -6 2 0 -8 -18 17; -10 9 17 4 8 0 -8 12; 0 12 1 0 18 8 0 0; 11 13 -18 -11 -17 -12 0 0])) == -119000 # test a few 4x4 Pfaffians against the analytical formula for i = 1:10 a,b,c,d,e,f = rand(-10:10,6) A = [0 a b c; -a 0 d e; -b -d 0 f; -c -e -f 0] @test SkewLinearAlgebra.exactpfaffian(A) == c*d - b*e + a*f ≈ pfaffian(A) end # issue #121 @test pfaffian([0 1 0 0; -1 0 0 0; 0 0 0 1; 0 0 -1 0]) == 1 end @testset "cholesky.jl" begin for T in (Int32, Float32, Float64), n in [1, 2, 10, 11] if T<:Integer A = skewhermitian(rand(convert(Array{T},-10:10), n, n)*T(2)) else A = skewhermitian(randn(T, n, n)) end C = skewchol(A) @test transpose(C.R) * C.J *C.R ≈ A.data[C.p, C.p] B = Matrix(A) C = skewchol(B) @test transpose(C.R)* C.J *C.R ≈ B[C.p, C.p] end end @testset "jmatrix.jl" begin for T in (Int32, Float32, Float64), n in [1, 2, 10, 11], sgn in (+1,-1) A = rand(T, n, n) J = JMatrix{T,sgn}(n) vec = zeros(T, n - 1) vec[1:2:n-1] .= -sgn Jtest = SkewHermTridiagonal(vec) @test size(J) == (n, n) @test size(J, 1) == n @test J == Matrix(J) == Matrix(Jtest) == SkewHermTridiagonal(J) @test A*Jtest ≈ A*J @test Jtest*A ≈ J*A Jtest2 = Matrix(J) @test -J == -Jtest2 @test transpose(J) == -Jtest2 == J' if iseven(n) @test inv(J) == -Jtest2 @test J \ A ≈ Matrix(J) \ A @test A / J ≈ A / Matrix(J) end for k in [-4:4; n; n+1] @test diag(J, k) == diag(Jtest2, k) end @test iszero(tr(J)) @test iseven(n) == det(J) ≈ det(Jtest2) end @test repr("text/plain", JMatrix(4)) == "4×4 JMatrix{Int8, 1}:\n ⋅ 1 ⋅ ⋅\n -1 ⋅ ⋅ ⋅\n ⋅ ⋅ ⋅ 1\n ⋅ ⋅ -1 ⋅" end @testset "issue#116" begin for ev in ([0,0,0], [1,2,3,2,1], [0,1,0], [1,0,0], [1,0,1], [1,1,0], [0,1,1], [0,0,1], [1,1,1],[1,1,0,1,1],[0,0,0,0,1,1,1],[0,1,0,1,0,1,1,1,0,0,0,1]) A = SkewHermTridiagonal(float.(ev)) a = sort(eigvals(A), by = imag) b = sort(eigvals(im * Matrix(A)) / im, by = imag) @test a ≈ b E = eigen(A) @test E.vectors*Diagonal(E.values)*E.vectors'≈A end for ev in ([1,1,0,1],[0,1,0,1,1,1,1,1]) A = SkewHermTridiagonal(float.(ev)) a = sort(eigvals(A), by = imag) b = sort(eigvals(im * Matrix(A)) / im, by = imag) @test a ≈ b E = eigen(A) @test E.vectors*Diagonal(E.values)*E.vectors'≈A end end @testset "issue#118 and issue#130" begin #issue #130 sp = sparse([2, 7, 1, 3, 6, 8, 2, 4, 7, 9, 3, 5, 8, 10, 4, 9, 2, 7, 1, 3, 6, 8, 2, 4, 7, 9, 3, 5, 8, 10, 4, 9], [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10], [-0.8414709848, 1.5403023059, 0.8414709848, -0.8414709848, 0.4596976941, 1.5403023059, 0.8414709848, -0.8414709848, 0.4596976941, 1.5403023059, 0.8414709848, -0.8414709848, 0.4596976941, 1.5403023059, 0.8414709848, 0.4596976941, -0.4596976941, 0.8414709848, -1.5403023059, -0.4596976941, -0.8414709848, 0.8414709848, -1.5403023059, -0.4596976941, -0.8414709848, 0.8414709848, -1.5403023059, -0.4596976941, -0.8414709848, 0.8414709848, -1.5403023059, -0.8414709848], 10, 10) A = SkewHermitian(Matrix(sp)) E = eigen(A) @test E.vectors*Diagonal(E.values)*E.vectors' ≈ A sp = sparse([26, 50, 51, 52, 27, 51, 52, 53, 28, 52, 53, 54, 29, 53, 54, 55, 30, 54, 55, 56, 31, 55, 56, 32, 33, 57, 58, 32, 33, 34, 57, 58, 59, 33, 34, 35, 58, 59, 60, 34, 35, 36, 59, 60, 61, 35, 36, 37, 60, 61, 62, 36, 37, 38, 61, 62, 63, 37, 38, 39, 62, 63, 64, 38, 39, 40, 63, 64, 65, 39, 40, 41, 64, 65, 66, 40, 41, 42, 65, 66, 41, 42, 43, 66, 42, 43, 44, 43, 44, 45, 44, 45, 46, 45, 46, 47, 46, 47, 48, 47, 48, 49, 48, 49, 50, 49, 50, 51, 1, 50, 51, 52, 2, 51, 52, 53, 3, 52, 53, 54, 4, 53, 54, 55, 5, 54, 55, 56, 6, 55, 56, 7, 8, 7, 8, 9, 58, 8, 9, 10, 59, 9, 10, 11, 60, 10, 11, 12, 61, 11, 12, 13, 62, 12, 13, 14, 63, 13, 14, 15, 64, 14, 15, 16, 65, 15, 16, 17, 66, 16, 17, 18, 17, 18, 19, 18, 19, 20, 19, 20, 21, 20, 21, 22, 21, 22, 23, 22, 23, 24, 23, 24, 25, 1, 24, 25, 26, 1, 2, 25, 26, 27, 1, 2, 3, 26, 27, 28, 2, 3, 4, 27, 28, 29, 3, 4, 5, 28, 29, 30, 4, 5, 6, 29, 30, 31, 5, 6, 30, 31, 7, 8, 7, 8, 9, 33, 8, 9, 10, 34, 9, 10, 11, 35, 10, 11, 12, 36, 11, 12, 13, 37, 12, 13, 14, 38, 13, 14, 15, 39, 14, 15, 16, 40, 15, 16, 17, 41], [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 33, 34, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, 38, 38, 38, 38, 39, 39, 39, 39, 40, 40, 40, 40, 41, 41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46, 46, 47, 47, 47, 48, 48, 48, 49, 49, 49, 50, 50, 50, 50, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 56, 56, 56, 56, 57, 57, 58, 58, 58, 58, 59, 59, 59, 59, 60, 60, 60, 60, 61, 61, 61, 61, 62, 62, 62, 62, 63, 63, 63, 63, 64, 64, 64, 64, 65, 65, 65, 65, 66, 66, 66, 66], [-1.176e-13, -0.0980580675690928, 0.987744983947536, -0.0980580675690911, -4.9e-14, -0.0980580675690911, 0.987744983947536, -0.0980580675690927, 1.96e-14, -0.0980580675690927, 0.987744983947536, -0.098058067569091, -1.96e-13, -0.098058067569091, 0.987744983947536, -0.0980580675690928, -1.274e-13, -0.0980580675690928, 0.987744983947536, -0.0980580675690928, -5.88e-14, -0.0980580675690928, 0.987744983947536, -10.0, -0.4902903378454601, -100.97143868952186, -0.098058067569092, 0.4902903378454601, -10.0, -0.4902903378454601, -0.098058067569092, -100.97143868952186, -0.098058067569092, 0.4902903378454601, -10.0, -0.4902903378454601, -0.098058067569092, -100.97143868952186, -0.0980580675690921, 0.4902903378454601, -10.0, -0.4902903378454601, -0.0980580675690921, -100.97143868952186, -0.0980580675690919, 0.4902903378454601, -10.0, -0.4902903378454601, -0.0980580675690919, -100.97143868952186, -0.0980580675690919, 0.4902903378454601, -10.0, -0.49029033784546, -0.0980580675690919, -100.97143868952186, -0.0980580675690923, 0.49029033784546, -10.0, -0.4902903378454601, -0.0980580675690923, -100.97143868952186, -0.0980580675690919, 0.4902903378454601, -10.0, -0.4902903378454601, -0.0980580675690919, -100.97143868952186, -0.0980580675690919, 0.4902903378454601, -10.0, -0.4902903378454601, -0.0980580675690919, -100.97143868952186, -0.0980580675690919, 0.4902903378454601, -10.0, -0.4902903378454601, -0.0980580675690919, -100.97143868952186, 0.4902903378454601, -10.0, -0.4902903378454601, -0.0980580675690919, 0.4902903378454601, -10.0, -0.4902903378454599, 0.4902903378454599, -10.0, -0.4902903378454603, 0.4902903378454603, -10.0, -0.4902903378454599, 0.4902903378454599, -10.0, -0.4902903378454602, 0.4902903378454603, -10.0, -0.4902903378454599, 0.4902903378454599, -10.0, -0.4902903378454599, 0.4902903378454599, -10.0, -0.4902903378454603, 0.4902903378454603, -10.0, -0.4902903378454599, 1.176e-13, 0.4902903378454599, -10.0, -0.4902903378454602, 4.9e-14, 0.4902903378454602, -10.0, -0.4902903378454599, -1.96e-14, 0.4902903378454599, -10.0, -0.4902903378454603, 1.96e-13, 0.4902903378454603, -10.0, -0.4902903378454599, 1.274e-13, 0.4902903378454599, -10.0, -0.4902903378454599, 5.88e-14, 0.4902903378454599, -10.0, 10.0, -0.4902903378454601, 0.4902903378454601, 10.0, -0.4902903378454601, 2.4e-15, 0.4902903378454601, 10.0, -0.4902903378454601, 4.9e-15, 0.4902903378454601, 10.0, -0.4902903378454601, 7.3e-15, 0.4902903378454601, 10.0, -0.4902903378454601, 9.8e-15, 0.4902903378454601, 10.0, -0.49029033784546, 1.22e-14, 0.49029033784546, 10.0, -0.4902903378454601, 1.47e-14, 0.4902903378454601, 10.0, -0.4902903378454601, 1.71e-14, 0.4902903378454601, 10.0, -0.4902903378454601, 1.96e-14, 0.4902903378454601, 10.0, -0.4902903378454601, 2.2e-14, 0.4902903378454601, 10.0, -0.4902903378454601, 0.4902903378454601, 10.0, -0.4902903378454599, 0.4902903378454599, 10.0, -0.4902903378454603, 0.4902903378454603, 10.0, -0.4902903378454599, 0.4902903378454599, 10.0, -0.4902903378454603, 0.4902903378454602, 10.0, -0.4902903378454599, 0.4902903378454599, 10.0, -0.4902903378454599, 0.4902903378454599, 10.0, -0.4902903378454603, 0.0980580675690928, 0.4902903378454603, 10.0, -0.4902903378454599, -0.987744983947536, 0.0980580675690911, 0.4902903378454599, 10.0, -0.4902903378454602, 0.0980580675690911, -0.987744983947536, 0.0980580675690927, 0.4902903378454602, 10.0, -0.4902903378454599, 0.0980580675690927, -0.987744983947536, 0.098058067569091, 0.4902903378454599, 10.0, -0.4902903378454603, 0.098058067569091, -0.987744983947536, 0.0980580675690928, 0.4902903378454603, 10.0, -0.4902903378454599, 0.0980580675690928, -0.987744983947536, 0.0980580675690928, 0.4902903378454599, 10.0, -0.4902903378454599, 0.0980580675690928, -0.987744983947536, 0.4902903378454599, 10.0, 100.97143868952186, 0.098058067569092, 0.098058067569092, 100.97143868952186, 0.098058067569092, -2.4e-15, 0.098058067569092, 100.97143868952186, 0.0980580675690921, -4.9e-15, 0.0980580675690921, 100.97143868952186, 0.0980580675690919, -7.3e-15, 0.0980580675690919, 100.97143868952186, 0.0980580675690919, -9.8e-15, 0.0980580675690919, 100.97143868952186, 0.0980580675690923, -1.22e-14, 0.0980580675690923, 100.97143868952186, 0.0980580675690919, -1.47e-14, 0.0980580675690919, 100.97143868952186, 0.0980580675690919, -1.71e-14, 0.0980580675690919, 100.97143868952186, 0.0980580675690919, -1.96e-14, 0.0980580675690919, 100.97143868952186, 0.0980580675690919, -2.2e-14], 66, 66) A = SkewHermitian(Matrix(sp)) E = eigen(A) @test E.vectors*Diagonal(E.values)*E.vectors' ≈ A #issue #118 for v ∈ ([1.0, 0.001, 1.0, 0.0001, 1.0], [2.0, 1e-11, 2.0, 1e-11, 2.0]) A = SkewHermTridiagonal(v) E = eigen(A) @test E.vectors*Diagonal(E.values)*E.vectors' ≈ A B = SkewHermitian(Matrix(A)) E = eigen(B) @test E.vectors*Diagonal(E.values)*E.vectors' ≈ B end end
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
1540
[![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl/blob/main/LICENSE) [![Build Status](https://github.com/JuliaLinearAlgebra/IterativeSolvers.jl/workflows/CI/badge.svg)](https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl/actions) [![Codecov](http://codecov.io/github/JuliaLinearAlgebra/SkewLinearAlgebra.jl/coverage.svg?branch=main)](http://codecov.io/github/JuliaLinearAlgebra/SkewLinearAlgebra.jl?branch=main) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://julialinearalgebra.github.io/SkewLinearAlgebra.jl/dev/) # SkewLinearAlgebra The `SkewLinearAlgebra` package provides specialized matrix types, optimized methods of `LinearAlgebra` functions, and a few entirely new functions for dealing with linear algebra on [skew-Hermitian matrices](https://en.wikipedia.org/wiki/Skew-Hermitian_matrix), especially for the case of [real skew-symmetric matrices](https://en.wikipedia.org/wiki/Skew-symmetric_matrix). In particular, it defines new `SkewHermitian` and `SkewHermTridiagonal` matrix types supporting optimized eigenvalue/eigenvector, Hessenberg factorization, and matrix exponential/trigonometric functions. It also provides functions to compute the [Pfaffian](https://en.wikipedia.org/wiki/Pfaffian) of skew-symmetric matrices, along with a Cholesky-like factorization for real skew-symmetric matrices. See the [Documentation](https://julialinearalgebra.github.io/SkewLinearAlgebra.jl/dev/) for details.
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
7276
## Skew-Hermitian eigenproblems A skew-Hermitian matrix ``A = -A^*`` is very special with respect to its eigenvalues/vectors and related properties: * It has **purely imaginary** eigenvalues. (If ``A`` is real, these come in **± pairs** or are zero.) * We can always find [orthonormal](https://en.wikipedia.org/wiki/Orthonormality) eigenvectors (``A`` is [normal](https://en.wikipedia.org/wiki/Normal_matrix)). By wrapping a matrix in the [`SkewHermitian`](@ref) or [`SkewHermTridiagonal`](@ref) types, you can exploit optimized methods for eigenvalue calculations (extending the functions defined in Julia's `LinearAlgebra` standard library). Especially for *real* skew-symmetric ``A=-A^T``, these optimized methods are generally *much faster* than the alternative of forming the complex-Hermitian matrix ``iA``, computing its diagonalization, and multiplying the eigenvalues by ``-i``. In particular, optimized methods are provided for [`eigen`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigen) (returning a factorization object storing both eigenvalues and eigenvectors), [`eigvals`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigvals) (just eigenvalues), [`eigvecs`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigvecs) (just eigenvectors), and their in-place variants [`eigen!`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigen!)/[`eigvals!`] (which overwrite the matrix data). Since the [SVD](https://en.wikipedia.org/wiki/Singular_value_decomposition) and [Schur](https://en.wikipedia.org/wiki/Schur_decomposition) factorizations can be trivially computed from the eigenvectors/eigenvalues for any normal matrix, we also provide optimized methods for [`svd`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.svd), [`svdvals`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.svdvals), [`schur`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.schur), and their in-place variants [`svd!`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.svd!)/[`svdvals!`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.svdvals!)/[`schur!`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.schur!). A key intermediate step in solving eigenproblems is computing the Hessenberg tridiagonal reduction of the matrix, and we expose this functionality by providing optimized [`hessenberg`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.hessenberg) and [`hessenberg!`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.hessenberg!) methods for `SkewHermitian` matrices as described below. (The Hessenberg tridiagonalization is sometimes useful in its own right for matrix computations.) ### Eigenvalues and eigenvectors The package also provides eigensolvers for `SkewHermitian` and `SkewHermTridiagonal` matrices. A fast and sparse specialized QR algorithm is implemented for `SkewHermTridiagonal` matrices and also for `SkewHermitian` matrices using the `hessenberg` reduction. The function `eigen` returns a `Eigen`structure as the LinearAlgebra standard library: ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = SkewHermitian([0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0]); julia> E = eigen(A) Eigen{ComplexF64, ComplexF64, Matrix{ComplexF64}, Vector{ComplexF64}} values: 4-element Vector{ComplexF64}: 0.0 + 11.934458713974193im 0.0 + 0.7541188264752741im -0.0 - 0.7541188264752989im -0.0 - 11.934458713974236im vectors: 4×4 Matrix{ComplexF64}: -0.49111+0.0im -0.508735+0.0im 0.508735+0.0im 0.49111+0.0im -0.488014-0.176712im 0.471107+0.0931315im -0.471107+0.0931315im 0.488014-0.176712im -0.143534+0.615785im 0.138561-0.284619im -0.138561-0.284619im 0.143534+0.615785im -0.00717668-0.299303im 0.00692804-0.640561im -0.00692804-0.640561im 0.00717668-0.299303im ``` The function `eigvals` provides the eigenvalues of ``A``. The eigenvalues can be sorted and found partially with imaginary part in some given real range or by order. ```jl julia> eigvals(A) 4-element Vector{ComplexF64}: 0.0 + 11.93445871397423im 0.0 + 0.7541188264752853im -0.0 - 0.7541188264752877im -0.0 - 11.934458713974225im julia> eigvals(A,0,15) 2-element Vector{ComplexF64}: 0.0 + 11.93445871397414im 0.0 + 0.7541188264752858im julia> eigvals(A,1:3) 3-element Vector{ComplexF64}: 0.0 + 11.93445871397423im 0.0 + 0.7541188264752989im -0.0 - 0.7541188264752758im ``` ### SVD A specialized SVD using the eigenvalue decomposition is implemented for `SkewHermitian` and `SkewHermTridiagonal` type. These functions can be called using the `LinearAlgebra` syntax. ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = SkewHermitian([0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0]); julia> svd(A) SVD{ComplexF64, Float64, Matrix{ComplexF64}} U factor: 4×4 Matrix{ComplexF64}: 0.49111+0.0im -0.49111+0.0im 0.508735+0.0im -0.508735+0.0im 0.488014-0.176712im -0.488014-0.176712im -0.471107+0.0931315im 0.471107+0.0931315im 0.143534+0.615785im -0.143534+0.615785im -0.138561-0.284619im 0.138561-0.284619im 0.00717668-0.299303im -0.00717668-0.299303im -0.00692804-0.640561im 0.00692804-0.640561im singular values: 4-element Vector{Float64}: 11.93445871397423 11.934458713974193 0.7541188264752989 0.7541188264752758 Vt factor: 4×4 Matrix{ComplexF64}: 0.0-0.49111im 0.176712-0.488014im -0.615785-0.143534im 0.299303-0.00717668im 0.0-0.49111im -0.176712-0.488014im 0.615785-0.143534im -0.299303-0.00717668im 0.0-0.508735im -0.0931315+0.471107im 0.284619+0.138561im 0.640561+0.00692804im 0.0-0.508735im 0.0931315+0.471107im -0.284619+0.138561im -0.640561+0.00692804im julia> svdvals(A) 4-element Vector{Float64}: 11.93445871397423 11.934458713974225 0.7541188264752877 0.7541188264752853 ``` ### Hessenberg tridiagonalization The Hessenberg reduction performs a reduction ``A=QHQ^T`` where ``Q=\prod_i I-\tau_i v_iv_i^T`` is an orthonormal matrix. The `hessenberg` function computes the Hessenberg decomposition of `A` and returns a `Hessenberg` object. If `F` is the factorization object, the unitary matrix can be accessed with `F.Q` (of type `LinearAlgebra.HessenbergQ`) and the Hessenberg matrix with `F.H` (of type `SkewHermTridiagonal`), either of which may be converted to a regular matrix with `Matrix(F.H)` or `Matrix(F.Q)`. ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = SkewHermitian([0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0]); julia> hessenberg(A) Hessenberg{Float64, Tridiagonal{Float64, Vector{Float64}}, Matrix{Float64}, Vector{Float64}, Bool} Q factor: 4×4 LinearAlgebra.HessenbergQ{Float64, Matrix{Float64}, Vector{Float64}, true}: 1.0 0.0 0.0 0.0 0.0 -0.240772 -0.95927 -0.14775 0.0 0.842701 -0.282138 0.458534 0.0 -0.481543 -0.0141069 0.876309 H factor: 4×4 SkewHermTridiagonal{Float64, Vector{Float64}, Nothing}: 0.0 -8.30662 0.0 0.0 8.30662 0.0 -8.53382 0.0 0.0 8.53382 0.0 1.08347 0.0 0.0 -1.08347 0.0 ```
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
4084
# SkewLinearAlgebra The `SkewLinearAlgebra` package provides specialized matrix types, optimized methods of `LinearAlgebra` functions, and a few entirely new functions for dealing with linear algebra on [skew-Hermitian matrices](https://en.wikipedia.org/wiki/Skew-Hermitian_matrix), especially for the case of [real skew-symmetric matrices](https://en.wikipedia.org/wiki/Skew-symmetric_matrix). ## Introduction A skew-Hermitian matrix ``A`` is a square matrix that equals the negative of its conjugate-transpose: ``A=-\overline{A^{T}}=-A^{*}``, equivalent to `A == -A'` in Julia. (In the real skew-symmetric case, this is simply ``A=-A^T``.) Such matrices have special computational properties: orthogonal eigenvectors and purely imaginary eigenvalues, "skew-Cholesky" factorizations, and a relative of the determinant called the [Pfaffian](https://en.wikipedia.org/wiki/Pfaffian). Although any skew-Hermitian matrix ``A`` can be transformed into a Hermitian matrix ``H=iA``, this transformation converts real matrices ``A`` into complex-Hermitian matrices ``H``, which entails at least a factor of two loss in performance and memory usage compared to the real case. (And certain operations, like the Pfaffian, are *only* defined for the skew-symmetric case.) `SkewLinearAlgebra` gives you access to the greater performance and functionality that are possible for purely real skew-symmetric matrices. To achieve this `SkewLinearAlgebra` defines a new matrix type, [`SkewHermitian`](@ref SkewLinearAlgebra.SkewHermitian) (analogous to the [`LinearAlgebra.Hermitian`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.Hermitian) type in the Julia standard library) that gives you access to optimized methods and specialized functionality for skew-Hermitian matrices, especially in the real case. It also provides a more specialized [`SkewHermTridiagonal`](@ref SkewLinearAlgebra.SkewHermTridiagonal) for skew-Hermitian tridiagonal matrices (analogous to the [`LinearAlgebra.SymTridiagonal`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.SymTridiagonal) type in the Julia standard library) . ## Contents The `SkewLinearAlgebra` documentation is divided into the following sections: * [Skew-Hermitian matrices](@ref): the `SkewHermitian` type, constructors, and basic operations * [Skew-Hermitian tridiagonal matrices](@ref): the `SkewHermTridiagonal` type, constructors, and basic operations * [Skew-Hermitian eigenproblems](@ref): optimized eigenvalues/eigenvectors (& Schur/SVD), and Hessenberg factorization * [Trigonometric functions](@ref): optimized matrix exponentials and related functions (`exp`, `sin`, `cos`, etcetera) * [Pfaffian calculations](@ref): computation of the Pfaffian and log-Pfaffian * [Skew-Cholesky factorization](@ref): a skew-Hermitian analogue of Cholesky factorization ## Quick start Here is a simple example demonstrating some of the features of the `SkewLinearAlgebra` package. See the manual chapters outlines above for the complete details and explanations: ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = SkewHermitian([0 1 2 -1 0 3 -2 -3 0]) 3×3 SkewHermitian{Int64, Matrix{Int64}}: 0 1 2 -1 0 3 -2 -3 0 julia> eigvals(A) # optimized eigenvalue calculation (purely imaginary) 3-element Vector{ComplexF64}: 0.0 - 3.7416573867739404im 0.0 + 3.7416573867739404im 0.0 + 0.0im julia> Q = exp(A) # optimized matrix exponential 3×3 Matrix{Float64}: 0.348107 -0.933192 0.0892929 -0.63135 -0.303785 -0.713521 0.692978 0.192007 -0.694921 julia> Q'Q ≈ I # the exponential of a skew-Hermitian matrix is unitary true julia> pfaffian(A) # the Pfaffian (always zero for odd-size skew matrices) 0.0 ``` ## Acknowledgements The `SkewLinearAlgebra` package was initially created by [Simon Mataigne](https://github.com/smataigne) and [Steven G. Johnson](https://math.mit.edu/~stevenj/), with support from [UCLouvain](https://uclouvain.be/) and the [MIT–Belgium program](https://misti.mit.edu/mit-belgium).
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
3699
# Pfaffian calculations A skew-symmetrix matrix ``A = -A^T`` has a special property: its determinant is the square of a polynomial function of the matrix entries, called the [Pfaffian](https://en.wikipedia.org/wiki/Pfaffian). That is, ``\mathrm{det}(A) = \mathrm{Pf}(A)^2``, but knowing the Pfaffian itself (and its sign, which is lost in the determinant) is useful for a number of applications. We provide a function `pfaffian(A)` to compute the Pfaffian of a skew-symmetric matrix `A`. ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = [0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0] 4×4 Matrix{Int64}: 0 2 -7 4 -2 0 -8 3 7 8 0 1 -4 -3 -1 0 julia> pfaffian(A) -9.000000000000002 julia> det(A) # exact determinant is (-9)^2 80.99999999999999 ``` By default, this computation is performed approximately using floating-point calculations, similar to Julia's [`det`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.det) algorithm for the determinant. However, for a [`BigInt` matrix](https://docs.julialang.org/en/v1/base/numbers/#BigFloats-and-BigInts), `pfaffian(A)` is computed exactly using an algorithm by [Galbiati and Maffioli (1994)](https://doi.org/10.1016/0166-218X(92)00034-J): ```jl julia> pfaffian(BigInt.(A)) -9 julia> det(big.(A)) # also exact for BigInt 81 ``` Note that you need not (but may) pass a `SkewHermitian` matrix type to `pfaffian`. However, because the Pfaffian is only defined for skew-symmetric matrices, it will give an error if you pass it a non-skewsymmetric matrix: ```jl julia> pfaffian([1 2 3; 4 5 6; 7 8 9]) ERROR: ArgumentError: Pfaffian requires a skew-Hermitian matrix ``` We also provide a function `pfaffian!(A)` that overwrites `A` in-place (with undocumented values), rather than making a copy of the matrix for intermediate calculations: ```jl julia> pfaffian!(BigInt[0 2 -7; -2 0 -8; 7 8 0]) 0 ``` (Note that the Pfaffian is *always zero* for any *odd* size skew-symmetric matrix.) Since the computation of the pfaffian can easily overflow/underflow the maximum/minimum representable floating-point value, we also provide a function `logabspfaffian` (along with an in-place variant `logabspfaffian!`) that returns a tuple `(logpf, sign)` such that the Pfaffian is `sign * exp(logpf)`. (This is similar to the [`logabsdet`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.logabsdet) function in Julia's `LinearAlgebra` library to compute the log of the determinant.) ```jl julia> logpf, sign = logabspfaffian(A) (2.1972245773362196, -1.0) julia> sign * exp(logpf) # matches pfaffian(A), up to floating-point rounding errors -9.000000000000002 julia> B = triu(rand(-9:9, 500,500)); B = B - B'; # 500×500 skew-symmetric matrix julia> pfaffian(B) # overflows double-precision floating point Inf julia> pf = pfaffian(big.(B)) # exact answer in BigInt precision (slow) -149678583522522720601879230931167588166888361287738234955688347466367975777696295859892310371985561723944757337655733584612691078889626269612647408920674699424393216780756729980039853434268507566870340916969614567968786613166601938742927283707974123631646016992038329261449437213872613766410239159659548127386325836018158542150965421313640795710036050440344289340146687857870477701301808699453999823930142237829465931054145755710674564378910415127367945223991977718726 julia> Float64(log(abs(pf))) # exactly rounded log(abs(pfaffian(B))) 1075.7105584607807 julia> logabspfaffian(B) # matches log and sign! (1075.71055846078, -1.0) ``` ### Pfaffian Reference ```@docs SkewLinearAlgebra.pfaffian SkewLinearAlgebra.pfaffian! SkewLinearAlgebra.logabspfaffian SkewLinearAlgebra.logabspfaffian! ```
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
1620
## Skew-Cholesky factorization The package provides a Cholesky-like factorization for real skew-symmetric matrices as presented in P. Benner et al, "[Cholesky-like factorizations of skew-symmetric matrices](https://etna.ricam.oeaw.ac.at/vol.11.2000/pp85-93.dir/pp85-93.pdf)"(2000). Every real skew-symmetric matrix ``A`` can be factorized as ``A=P^TR^TJRP`` where ``P`` is a permutation matrix, ``R`` is an `UpperTriangular` matrix and J is of a special type called `JMatrix` that is a tridiagonal skew-symmetric matrix composed of diagonal blocks of the form ``B=[0, 1; -1, 0]``. The `JMatrix` type implements efficient operations related to the shape of the matrix as matrix-matrix/vector multiplication and inversion. The function `skewchol` implements this factorization and returns a `SkewCholesky` structure composed of the matrices `Rm` and `Jm` of type `UpperTriangular` and `JMatrix` respectively. The permutation matrix ``P`` is encoded as a permutation vector `Pv`. ```jl julia> R = skewchol(A) julia> R.Rm 4×4 LinearAlgebra.UpperTriangular{Float64, Matrix{Float64}}: 2.82843 0.0 0.707107 -1.06066 ⋅ 2.82843 2.47487 0.353553 ⋅ ⋅ 1.06066 0.0 ⋅ ⋅ ⋅ 1.06066 julia> R.Jm 4×4 JMatrix{Float64, 1}: ⋅ 1.0 ⋅ ⋅ -1.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1.0 ⋅ ⋅ -1.0 ⋅ julia> R.Pv 4-element Vector{Int64}: 3 2 1 4 julia> transpose(R.Rm) * R.Jm * R.Rm ≈ A[R.Pv,R.Pv] true ``` ### Skew-Cholesky Reference ```@docs SkewLinearAlgebra.skewchol SkewLinearAlgebra.skewchol! SkewLinearAlgebra.SkewCholesky SkewLinearAlgebra.JMatrix ```
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
1729
## Trigonometric functions The package implements special methods of trigonometric matrix functions using our optimized eigenvalue decomposition for `SkewHermitian` and `SkewHermTridiagonal` matrices: `exp`, `cis`, `cos`, `sin`, `sincos`, `sinh`, and `cosh`. For example: ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = SkewHermitian([0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0]); julia> Q = exp(A) 4×4 Matrix{Float64}: -0.317791 -0.816528 -0.268647 0.400149 -0.697298 0.140338 0.677464 0.187414 0.578289 -0.00844255 0.40033 0.710807 0.279941 -0.559925 0.555524 -0.547275 ``` Note that the exponential of a skew-Hermitian matrix is very special: it is unitary. That is, if ``A^* = -A``, then ``(e^A)^* = (e^A)^{-1}``: ```jl julia> Q' ≈ Q^-1 true ``` Several of the other matrix trigonometric functions also have special return types, in addition to being optimized for performance. ```jl julia> cis(A) 4×4 Hermitian{ComplexF64, Matrix{ComplexF64}}: 36765.0+0.0im 36532.0+13228.5im … 537.235+22406.2im 36532.0-13228.5im 41062.9+0.0im 8595.76+22070.7im 10744.7+46097.2im -5909.58+49673.4im -27936.2+7221.87im 537.235-22406.2im 8595.76-22070.7im 13663.9+0.0im julia> cos(A) 4×4 Symmetric{Float64, Matrix{Float64}}: 36765.0 36532.0 10744.7 537.235 36532.0 41062.9 -5909.58 8595.76 10744.7 -5909.58 60940.6 -27936.2 537.235 8595.76 -27936.2 13663.9 julia> cosh(A) 4×4 Hermitian{Float64, Matrix{Float64}}: 0.766512 0.0374 0.011 0.000550001 0.0374 0.770912 -0.00605001 0.00880001 0.011 -0.00605001 0.791262 -0.0286 0.000550001 0.00880001 -0.0286 0.742862 ```
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
1.0.0
5d44a4f56f7902c4414c0a477b021f17cf088cb3
docs
6488
## Skew-Hermitian matrices [`SkewHermitian(A)`](@ref) wraps an existing matrix `A`, which *must* already be skew-Hermitian, in the `SkewHermitian` type (a subtype of `AbstractMatrix`), which supports fast specialized operations noted below. You can use the function [`isskewhermitian(A)`](@ref) to check whether `A` is skew-Hermitian (`A == -A'`). `SkewHermitian(A)` *requires* that `A == -A'` and throws an error if it is not. Alternatively, you can use the funcition [`skewhermitian(A)`](@ref) to take the skew-Hermitian *part* of `A`, defined by `(A - A')/2`, and wrap it in a `SkewHermitian` view. The function [`skewhermitian!(A)`](@ref) does the same operation in-place on `A` (overwriting `A` with its skew-Hermitian part). Here is a basic example to initialize a `SkewHermitian` matrix: ```jl julia> using SkewLinearAlgebra, LinearAlgebra julia> A = [0 2 -7 4; -2 0 -8 3; 7 8 0 1;-4 -3 -1 0] 3×3 Matrix{Int64}: 0 2 -7 4 -2 0 -8 3 7 8 0 1 -4 -3 -1 0 julia> isskewhermitian(A) true julia> A = SkewHermitian(A) 4×4 SkewHermitian{Int64, Matrix{Int64}}: 0 2 -7 4 -2 0 -8 3 7 8 0 1 -4 -3 -1 0 ``` Basic linear-algebra operations are supported: ```jl julia> tr(A) 0 julia> det(A) 81.0 julia> inv(A) 4×4 SkewHermitian{Float64, Matrix{Float64}}: 0.0 0.111111 -0.333333 -0.888889 -0.111111 0.0 0.444444 0.777778 0.333333 -0.444444 0.0 0.222222 0.888889 -0.777778 -0.222222 0.0 julia> x=[1;2;3;4] 4-element Vector{Int64}: 1 2 3 4 julia> A\x 4-element Vector{Float64}: -4.333333333333334 4.333333333333334 0.3333333333333336 -1.3333333333333333 ``` A `SkewHermitian` matrix `A` is simply a wrapper around an underlying matrix (in which both the upper and lower triangles are stored, despite the redundancy, to support fast matrix operations). You can extract this underlying matrix with the Julia [`parent(A)`](https://docs.julialang.org/en/v1/base/arrays/#Base.parent) function (this does *not* copy the data: mutating the parent will modify `A`). Alternatively, you can *copy* the data to an ordinary `Matrix` ([2d `Array`](https://docs.julialang.org/en/v1/manual/arrays/)) with `Matrix(A)`. ### Operations on `SkewHermitian` The `SkewHermitian` type supports the basic operations for any Julia `AbstractMatrix` (indexing, iteration, multiplication, addition, scaling, and so on). Matrix–matrix and matrix–vector multiplications are performed using the underlying parent matrix, so they are fast. We try to preserve the `SkewHermitian` wrapper, if possible. For example, adding two `SkewHermitian` matrices or scaling by a real number yields another `SkewHermitian` matrix. Similarly for `real(A)`, `conj(A)`, `inv(A)`, or `-A`. The package provides several optimized methods for `SkewHermitian` matrices, based on the functions defined by the Julia `LinearAlgebra` package: - Tridiagonal reduction: `hessenberg` - Eigensolvers: `eigen`, `eigvals` (also `schur`, `svd`, `svdvals`) - Trigonometric functions:`exp`, `cis`,`cos`,`sin`,`sinh`,`cosh`,`sincos` We also define the following *new* functions for real skew-symmetric matrices only: - Cholesky-like factorization: [`skewchol`](@ref) - Pfaffian: [`pfaffian`](@ref), [`logabspfaffian`](@ref) ## Skew-Hermitian tridiagonal matrices In the special case of a [tridiagonal](https://en.wikipedia.org/wiki/Tridiagonal_matrix) skew-Hermitian matrix, many calculations can be performed very quickly, typically with ``O(n)`` operations for an ``n\times n`` matrix. Such optimizations are supported by the `SkewLinearAlgebra` package using the `SkewHermTridiagonal` matrix type. A complex tridiagonal skew-Hermitian matrix is of the form: ```math A=\left(\begin{array}{ccccc} id_{1} & -e_{1}^{*}\\ e_{1} & id_{2} & -e_{2}^{*}\\ & e_{2} & id_{3} & \ddots\\ & & \ddots & \ddots & -e_{n-1}^{*}\\ & & & e_{n-1} & id_{n} \end{array}\right)=-A^{*} ``` with purely imaginary diagonal entries ``id_k``. This is represented in the `SkewLinearAlgebra` package by calling the `SkewHermTridiagonal(ev,dvim)` constructor, where `ev` is the (complex) vector of ``n-1`` subdiagonal entries ``e_k`` and `dvim` is the (real) vector of ``n`` diagonal imaginary parts ``d_k``: ```jl julia> SkewHermTridiagonal([1+2im,3+4im],[5,6,7]) 3×3 SkewHermTridiagonal{Complex{Int64}, Vector{Complex{Int64}}, Vector{Int64}}: 0+5im -1+2im ⋅ 1+2im 0+6im -3+4im ⋅ 3+4im 0+7im ``` In the case of a *real* matrix, the diagonal entries are zero, and the matrix takes the form: ```math \text{real }A=\left(\begin{array}{ccccc} 0 & -e_{1}\\ e_{1} & 0 & -e_{2}\\ & e_{2} & 0 & \ddots\\ & & \ddots & \ddots & -e_{n-1}\\ & & & e_{n-1} & 0 \end{array}\right)=-A^{T} ``` In this case, you need not store the zero diagonal entries, and can simply call `SkewHermTridiagonal(ev)` with the *real* vector `ev` of the ``n-1`` subdiagonal entries: ```jl julia> A = SkewHermTridiagonal([1,2,3]) 4×4 SkewHermTridiagonal{Int64, Vector{Int64}, Nothing}: ⋅ -1 ⋅ ⋅ 1 ⋅ -2 ⋅ ⋅ 2 ⋅ -3 ⋅ ⋅ 3 ⋅ ``` (Notice that zero values that are not stored (“structural zeros”) are shown as a `⋅`.) A `SkewHermTridiagonal` matrix can also be converted to the [`LinearAlgebra.Tridiagonal`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.SymTridiagonal) type in the Julia standard library: ```jl julia> Tridiagonal(A) 4×4 Tridiagonal{Int64, Vector{Int64}}: 0 -1 ⋅ ⋅ 1 0 -2 ⋅ ⋅ 2 0 -3 ⋅ ⋅ 3 0 ``` which may support a wider range of linear-algebra functions, but does not optimized for the skew-Hermitian structure. ### Operations on `SkewHermTridiagonal` The `SkewHermTridiagonal` type is modeled on the [`LinearAlgebra.SymTridiagonal`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.SymTridiagonal) type in the Julia standard library) and supports typical matrix operations (indexing, iteration, scaling, and so on). The package provides several optimized methods for `SkewHermTridiagonal` matrices, based on the functions defined by the Julia `LinearAlgebra` package: - Matrix-vector `A*x` and `dot(x,A,y)` products; also solves `A\x` (via conversion to `Tridiagonal`) - Eigensolvers: `eigen`, `eigvals` (also `svd`, `svdvals`) - Trigonometric functions:`exp`, `cis`,`cos`,`sin`,`sinh`,`cosh`,`sincos` ## Types Reference ```@docs SkewLinearAlgebra.SkewHermitian SkewLinearAlgebra.skewhermitian SkewLinearAlgebra.skewhermitian! SkewLinearAlgebra.SkewHermTridiagonal ```
SkewLinearAlgebra
https://github.com/JuliaLinearAlgebra/SkewLinearAlgebra.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
404
#= Multi-processing case. Requires Distributed to be installed. - Uncomment below, specifying number of desired processes (default is number of system cores) - Prefix all code below with `@everywhere` =# #= using Distributed addprocs(length(Sys.cpu_info())) @everywhere =# import Pkg Pkg.pkg"activate ." # using .MyPkg include("src/MyPkg.jl") Settings = MyPkg.Settings MyPkg.main(ARGS)
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
155
using Dance.Router function hello(headers::Dict{String, String}) :: String return "Hello World" end route("/", hello; method=GET, endpoint=EP_HTML)
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
291
module Conf """ Overwrite default config, 1 item per line See docs or `src/Configuration.jl.Settings` dict Format: param{Symbol}=value{Any} e.g: :dev = false """ :dev = false # Overwrite above values by reading from other file, depending on environment # E.g: include("dev.jl") end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1098
module MyPkg PROJECT_ROOT = abspath(".") Settings = [] import Dance #= STEP 1 If apart from `static_dir` as defined in `routes.jl` there are dirs to ignore adding to LOAD_PATH => add to `ignore_dirs` By default all other sub-dirs of project structure will be added =# ignore_dirs = [""] if Dance.populate_settings(PROJECT_ROOT) global Settings Settings = Dance.Configuration.Settings for item in Dance.populate_load_path(PROJECT_ROOT; ignore_dirs=ignore_dirs) push!(LOAD_PATH, item) end end #= STEP 2 Import modules here below, not above (STEP 1 populated `LOAD_PATH`) =# function main(args) if Dance.populate_router(PROJECT_ROOT) include(Settings[:routes_filename]*".jl") ## STEP 3: Add custom scripts here that need be run before launching Dance ## ############################################## start_server::Bool = true if length(args)>0 if args[1]=="repl" start_server = false end end Dance.launch(start_server) end end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
3812
module Configuration Settings = Dict( :api_access_control_allow_origin => "*", :dev => false, :html_base_filename => "html/base", :html_favicon_name => "html/favicon", :log_filename => "log/dancejl", :routes_filename => "routes", :server_host => "", :server_port => "" ) """ is_prod(file_path) Check if is Production environment """ function is_prod() :: Bool global Settings return !parse(Bool, Settings[:dev]) end """ populate(file_path) - Read settings/Global.jl from project - Populate/update Settings dict accordingly """ function populate(file_path) :: Bool is_success:Bool = false ### Parse project settings ### function parse() :: Nothing function _parse_file(path) :: Nothing open(path) do file for line in eachline(file) if length(line) > 0 # Trim left space line = lstrip(line) if startswith(line, "include(") _parse_file(joinpath( file_path, "settings", replace(replace(line, "include(\"" => ""), "\")" => "") )) elseif line[1]==':' line_split::Array{String} = split(line, "=") key::String = lstrip(rstrip(line_split[1]), ':') value::Union{Float64, Int64, String, SubString{String}} = lstrip(line_split[2]) # Remove trailing comment if occursin(" #", value) value = rstrip(split(value, " #")[1]) end # Remove enclosing quotation marks if is String value if value[1]=='"' value = lstrip(rstrip(value, '"'), '"') end # Convert SubString{String} from to String value = string(value) # Convert to Float/Int if possible if tryparse(Float64, value) isa Number if tryparse(Int64, value) !== nothing value = tryparse(Int64, value) else value = parse(Float64, value) end end # Populate/update Settings dict if haskey(Settings, Symbol(key)) global Settings Settings[Symbol(key)] = value else global Settings push!(Settings, Symbol(key) => value) end end end end end end return _parse_file(joinpath(file_path, "settings/Global.jl")) end parse() is_success = true ### Set default server values for Dev environment ### if !is_prod() if Settings[:server_host]=="" global Settings Settings[:server_host] = "127.0.0.1" end if Settings[:server_port] =="" global Settings Settings[:server_port] = 8000 end end ### Server values cannot be blank for Prod environment, as no default ### for key in [:server_host, :server_port] if Settings[key] == "" @error "Please set valid $key value, cannot be blank" is_success = false end end return is_success end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
6776
module Dance import Pkg import REPL include("Configuration.jl") include("Logger.jl") include("utils/URIUtils.jl") include("Router.jl") include("utils/PayloadUtils.jl") include("renderers/HTMLRenderer.jl") include("renderers/JSONRenderer.jl") include("renderers/StaticRenderer.jl") include("renderers/CoreRenderer.jl") include("engines/CoreEngine.jl") export start_project """ launch(start_server::Bool) Launch either (depending on `start_server` param): - Web server via selected engine - REPL """ function launch(start_server::Bool) :: Union{REPL.REPLBackend, Nothing} if start_server server_host::String = Configuration.Settings[:server_host] server_port::Int64 = Configuration.Settings[:server_port] @info "Web server started at $server_host:$server_port" CoreEngine.start_server(server_host, server_port) else # https://github.com/JuliaLang/julia/blob/master/stdlib/REPL/src/REPL.jl terminal = REPL.Terminals.TTYTerminal("", stdin, stdout, stderr) repl = REPL.LineEditREPL(terminal, true) REPL.run_repl(repl) end end """ populate_load_path(file_path::String; ignore_dirs::Array{String, 1}) - Read Settings dict for routes filepath - Get static dir by parsing routes.jl - Optional: array of other paths to ignore """ function populate_load_path(file_path::String; ignore_dirs::Array{String, 1}) :: Array{String, 1} dirs_ignore_array::Array{String, 1} = [".git", ".hg", "node_modules"] load_path_array::Array{String, 1} = [abspath(file_path)] function _get_static_dir() :: String static_dir::String = "" for line in readlines(joinpath(file_path, Configuration.Settings[:routes_filename]*".jl")) if occursin("static_dir(", line) static_dir = replace( strip( split( split( split(line, ",")[2], ")" )[1], "/" )[1] ), "\"" => "" ) end end return static_dir end function _populate_load_path() :: Nothing for item in readdir(file_path) if isdir(item) && !(item in filter(x -> !occursin("/", x), dirs_ignore_array)) for (root, dirs, files) in walkdir(item) push!(load_path_array, abspath(root)) for dir in dirs if size(split(root, "/"))[1]==1 for ignore_dir in dirs_ignore_array if !occursin(abspath(ignore_dir), abspath(joinpath(root))) if !(abspath(root) in load_path_array) push!(load_path_array, abspath(root)) end end end end ignore_dirs_contains_dir_counter::Int8 = 0 for ignore_dir in dirs_ignore_array if occursin(abspath(ignore_dir), abspath(joinpath(root, dir))) ignore_dirs_contains_dir_counter = 1 break end end if ignore_dirs_contains_dir_counter==0 if !(abspath(joinpath(root, dir)) in load_path_array) push!(load_path_array, abspath(joinpath(root, dir))) end end end end end end nothing end if _get_static_dir()!="" push!(dirs_ignore_array, _get_static_dir()) end dirs_ignore_array = vcat(dirs_ignore_array, ignore_dirs) _populate_load_path() return load_path_array end """ populate_router(file_path::String) Populate Router.ROUTES OrderedDict (when including/compiling Julia files) """ function populate_router(file_path::String) :: Bool return Router.populate(file_path) end """ populate_settings(file_path::String) Populate Configuration.Settings dict """ function populate_settings(file_path::String) :: Bool return Configuration.populate(file_path) end """ start_project(project_name::String, path::String=".") - Specify new project name - Copy `files` dir to root of new project """ function start_project(project_name::String, path::String=".") :: Nothing project_directory::String = joinpath(abspath(path), project_name) Pkg.generate(project_name) rm(joinpath(project_directory, "src"); recursive=true) for (root, dirs, files) in walkdir(joinpath(@__DIR__, "../files")) for file in files cp(joinpath(root, file), joinpath(project_directory, file); force=true) end for dir in dirs mkdir(joinpath(project_directory, dir)) for (root2, dirs2, files2) in walkdir(joinpath(root, dir)) for file in files2 cp(joinpath(root, dir, file), joinpath(project_directory, dir, file); force=true) end end end end project_name = titlecase(project_name) mv( joinpath(project_directory, "src/MyPkg.jl"), joinpath(project_directory, "src/$project_name.jl") ) for file_name in [ joinpath(project_directory, "src/$project_name.jl"), joinpath(project_directory, "dance.jl"), ] lines = readlines(file_name) open(file_name, "w") do io for line in lines if match(r"MyPkg", line) !== nothing line = replace(line, "MyPkg" => project_name) end println(io, line) end end end if Sys.iswindows() run(`icacls.exe $project_name /reset /T /Q`) run(`icacls "$project_name" /reset /T /Q`) username::String = read(run(`whoami`), String) run(`icacls.exe $project_name /grant $username:F /T /Q`) run(`icacls "$project_name" /grant "$username:(OI)(CI)(IO)F" /T /Q`) run(`icacls "$project_name" /grant "$username:F" /Q`) #= TODO: fix Windows PowerShell escape issue See: https://discourse.julialang.org/t/how-to-quote-special-characters-in-run-function/21359/4 =# @info "Please run REPL command `run(`attrib –r \"$project_name\\*.*\" /s`)` to finish (due to Julia <-> Windows PowerShell issue)" else run(`chmod -R 755 $project_directory`) end @info "Project files created for $project_name" end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
728
module Logger import Dates import Dance.Configuration """ log(error) Logging of timestamp & error message - If Prod: Write to log file - Else: Output te REPL """ function log(error::String) :: Nothing error::String = string(Dates.now(Dates.UTC), ": ", error) if Configuration.is_prod() log_filepath::String = Configuration.Settings[:log_filename]*".log" # Create logfile dir if not found if !isfile(log_filepath) paths::Array{String} = split(log_filepath, '/') mkpath(replace(log_filepath, paths[end] => "")) end open(log_filepath, "a+") do file write(file, error * "\n") end else @error error end end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
9669
module Router import OrderedCollections import Dance.Configuration import Dance.Logger import Dance.URIUtils include("mime_types.jl") const GET= "GET" const OPTIONS = "OPTIONS" const POST= "POST" const METHODS = [GET, OPTIONS, POST] const EP_HTML = "HTML" const EP_JSON = "JSON" const EP_STATIC = "STATIC" const ENDPOINTS = [EP_HTML, EP_JSON, EP_STATIC] STATIC_DIR = "" STATIC_ROUTE_PREFIX = "" export GET, POST, EP_HTML, EP_JSON, EP_STATIC, output_file_as_string, route, route_group, static_dir mutable struct Route endpoint::String method::String path::String has_regex::Bool action::Function html_file::String """ Route(;endpoint::String, method::String, path::String, has_regex::Bool, action::Function, html_file::String) Create new Route object, by validating supplied Route parameters """ function Route(;endpoint::String, method::String, path::String, has_regex::Bool, action::Function, html_file::String) :: Route error::String = "" if !(endpoint in ENDPOINTS) error = "Invalid endpoint. Must be \"EP_HTML\" or \"EP_JSON\" or \"EP_STATIC\"" elseif !(method in METHODS) error = "Invalid method. Must be \"GET\" or \"POST\"" elseif path_already_exists(path) error = "Path already exists" else try for item in split(path, "/") isa("r\"" * path * "\"", Regex) end catch e error = "Invalid route regex format" end try methods(action) catch e error = "Action function not defined" end end if length(error)==0 return new(endpoint, method, path, has_regex, action, html_file) else Logger.log("Route construction for `$path`: $error") end end end const ROUTES = OrderedCollections.OrderedDict{String, Route}() """ delete_routes!() Empty ROUTES ordered dict Only called from tests as of now """ function delete_routes!() :: OrderedCollections.OrderedDict{String, Route} empty!(ROUTES) end """ get_route(route_path::String) Search ROUTES ordered dict for route component from specified path """ function get_route(route_path::String) :: Union{Route, Nothing} found_route::Union{Route, Nothing} = nothing # Remove trailing slash (if not index url) route_path = remove_trailing_slash(route_path) for (path, route) in ROUTES if !route.has_regex if path==route_path found_route = route end else request_path_number_of_segments::Int8 = length(URIUtils.get_path_segments(route_path))[1] route_number_of_params::Int8 = length(collect(eachmatch(URIUtils.ROUTE_REGEX_BASIC_STRUCTURE, path))) if route.has_regex && request_path_number_of_segments==route_number_of_params try m::Union{RegexMatch, Nothing} = match(Regex(path), route_path) if isa(m, RegexMatch) && length(m.match)==length(route_path) found_route = route end catch e nothing end end end end if isnothing(found_route) Logger.log("Getting Route: route with path `$route_path` not defined") end return found_route end """ output_file_as_string(file_path::String) Read file_path as string and obtain corresponding mime-type based on file extension First try searching in STATIC_DIR then try in project root, each time relative to route_path `favicon.ico` is special exception case """ function output_file_as_string(file_path::String) :: Tuple{String, Dict} filename::String = "" file_output_as_string::String = "" headers::Dict{String, String} = Dict("Content-Type" => "") file_type::String = split(file_path, '.')[end] if file_type in keys(mime_types) headers["Content-Type"] = mime_types[file_type] else Logger.log("HTTP mime-type not yet supported for file: `$file_path`\nPlease file Github issue at: https://github.com/DanceJL/Dance.jl/issues") end if file_path=="/favicon.ico" filename = Configuration.Settings[:html_favicon_name] * ".ico" else try filename = STATIC_DIR * split(file_path, STATIC_ROUTE_PREFIX)[2] catch e filename = strip(file_path, '/') end end file_output_as_string = read(filename, String) headers["Content-Length"] = string(filesize(filename)) return file_output_as_string, headers end """ path_already_exists(path::String) Verify if ROUTES ordered dict already has existing entry for specified path """ function path_already_exists(path::String) :: Bool path_exists = false for route_path in keys(ROUTES) if route_path == path path_exists = true break end end return path_exists end """ populate(file_path) Register Routes from `Configuration.Settings[:routes_filename]` file """ function populate(file_path::String) :: Bool is_success::Bool = false routes_filepath::String = joinpath(file_path, Configuration.Settings[:routes_filename]*".jl") if isfile(routes_filepath) is_success = true else @error "Populating Routes: file not found at $routes_filepath" end # Add favicon.ico route("/favicon.ico", output_file_as_string; method=GET, endpoint=EP_STATIC) return is_success end """ remove_trailing_slash(path::String) Remove eventual trailing slash, if not index url """ function remove_trailing_slash(path::String) :: String if length(path)>1 && path[end]=='/' path = chop(path) end return path end """ route(path::Union{Regex, String}, action::Function; method::String=POST, endpoint=EP_JSON, html_file::String=Configuration.Settings[:html_base_filename]*".html") Create new Route and add to ROUTES ordered dict - If path is Regex, convert to String for storage (Route has `has_regex` field) - Remove trailing slash """ function route(path::Union{Regex, String}, action::Function; method::String=POST, endpoint::String=EP_JSON, html_file::String=Configuration.Settings[:html_base_filename]*".html") :: OrderedCollections.OrderedDict{String, Route} has_regex::Bool = isa(path, Regex) if has_regex path::String = replace(rstrip(string(path), '"'), "r\""=>"") end path = remove_trailing_slash(path) # Prevent route paths contaning dots at start (static files relative path) if startswith(path, "/..") @error "Route paths cannot go higher than project route in directory structure" end # Route path must have leading slash if !startswith(path, "/") @error "Route must start with leading slash" end push!(ROUTES, path => Route(endpoint=endpoint, method=method, path=path, has_regex=has_regex, action=action, html_file=html_file)) end """ route_group(routes::Array; route_prefix::String="", method::String="", endpoint::String="", html_file::String=Configuration.Settings[:html_base_filename]*".html") Loop through array of named tuple routes, calling `route` function - automatically prepend route_prefix to route path (if supplied) - if other parameters supplied as function kwargs, set route parameters accordingly """ function route_group(routes::Array; route_prefix::String="", method::String="", endpoint::String="", html_file::String=Configuration.Settings[:html_base_filename]*".html") :: Union{Nothing, OrderedCollections.OrderedDict{String, Route}} for item in routes if isa(item, NamedTuple) path::Union{Regex, String} = "" for idx in [:path, :action] if !(idx in keys(item)) @error "Please make sure $item contains at least `path` and `action` keys" end end if length(route_prefix)>0 && route_prefix!="/" if isa(item.path, Regex) path = Regex(route_prefix * string(item.path)[3:end-1]) else path = route_prefix * item.path end else path = item.path route_prefix = "" end if :method in keys(item) method = item.method end if :endpoint in keys(item) endpoint = item.endpoint end if :html_file in keys(item) html_file = item.html_file end route(path, item.action; method=method, endpoint=endpoint, html_file=html_file) else @error "Please supply route $item as NamedTuple" end end end """ static_dir(route_prefix::String, dir_path::String) Parse supplied directory path and create routes for each item """ function static_dir(route_prefix::String, dir_path::String) :: Nothing global STATIC_DIR = dir_path global STATIC_ROUTE_PREFIX = route_prefix for (root, dirs, files) in walkdir(dir_path) for file in files if !occursin(".DS_Store", file) path::String = STATIC_ROUTE_PREFIX * split(joinpath(root, file), STATIC_DIR)[2] # Windows path issue (replace backslash by forward slash) if Sys.iswindows() path = replace(path, "\\" => "/") end route(path, output_file_as_string; method=GET, endpoint=EP_STATIC) end end end end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
302
mime_types = Dict( "css" => "text/css", "gif" => "image/gif", "ico" => "image/x-icon", "jpe" => "image/jpeg", "jpeg" => "image/jpeg", "jpg" => "image/jpeg", "js" => "text/javascript", "pdf" => "application/pdf", "svg" => "image/svg+xml", "txt" => "text/plain" )
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
10892
module CoreEngine import DataFrames import JSON3 import Dance.Configuration import Dance.CoreRenderer import Dance.Logger import Dance.Router import Dance.PayloadUtils import Dance.URIUtils include("FlamencoEngine.jl") const OUTPUT_DATA_FORMATS = Union{DataFrames.DataFrame, Dict, String} const ROUTE_PARAMS_FORMATS = Union{Float64, Int64, String} """ build_route_params_dict(;request_route_segments::Array{String, 1}, route_path::String) :: Dict Build dict of route params and corresponding values, by: - Parsing route.path for only segment sections - Looking-up request route segments at corresponding index """ function build_route_params_dict(;request_route_segments::Array{String, 1}, route_path::String) :: Dict route_params_dict::Dict{Symbol, ROUTE_PARAMS_FORMATS} = Dict() for (idx, item) in enumerate(collect(eachmatch(URIUtils.ROUTE_REGEX_PARAM_ONLY, route_path))) index::String = lstrip(split(item.match, ">")[1], '<') value::ROUTE_PARAMS_FORMATS = request_route_segments[idx] if tryparse(Float64, value) isa Number if tryparse(Int64, value) !== nothing value = parse(Int64, value) else value = parse(Float64, value) end end route_params_dict[Symbol(index)] = value end return route_params_dict end """ map_route_function_output() Output from route.action can contain optional HTTP Headers params dict """ function map_route_function_output(output::Union{Tuple, OUTPUT_DATA_FORMATS}) data::OUTPUT_DATA_FORMATS = "" headers::Dict{String, String} = Dict() if isa(output, Tuple) data = output[1] headers = output[2] else data = output end return headers, data end """ process_backend_function(;route::Router.Route, route_segments::Array{String, 1}, payload::String, headers::Dict{String, String}) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} 2 main cases - JSON POST request with payload - GET request If error during process, render 500 response Render 400 if badly supplied payload data """ function process_backend_function(;route::Router.Route, route_segments::Array{String, 1}, payload::String, headers::Dict{String, String}) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} data::OUTPUT_DATA_FORMATS = "" output_headers::Dict{String, String} = Dict() output::Union{Tuple, OUTPUT_DATA_FORMATS} = "" received_data::Union{DataFrames.DataFrame, Union{Array{Any,1}, Dict}} = Dict() rendered_dict::Dict{Symbol, Union{Dict{String, String}, Int16, String}} = Dict() route_params_dict::Dict{Symbol, ROUTE_PARAMS_FORMATS} = Dict() if route.endpoint==Router.EP_JSON && length(payload)>0 can_proceed::Bool = false try json_decoded_data::Union{JSON3.Array, JSON3.Object} = JSON3.read(payload) if isa(json_decoded_data, JSON3.Array) received_data = PayloadUtils.convert_array_to_dataframe(json_decoded_data) else received_data = Dict(json_decoded_data) end can_proceed = true catch e rendered_dict = render_400(;endpoint=route.endpoint) end if can_proceed try if route.has_regex route_params_dict = build_route_params_dict(;request_route_segments=route_segments, route_path=route.path) output = route.action(route_params_dict, received_data, headers) else output = route.action(received_data, headers) end output_headers, data = map_route_function_output(output) rendered_dict = render_200(;headers=output_headers, endpoint=route.endpoint, data=data, html_file=route.html_file) catch e rendered_dict = render_500(;endpoint=route.endpoint, data=e, html_file=route.html_file, request_path=route.path) end end elseif route.endpoint==Router.EP_JSON || route.endpoint==Router.EP_HTML try if route.has_regex route_params_dict = build_route_params_dict(;request_route_segments=route_segments, route_path=route.path) output = route.action(route_params_dict, headers) else output = route.action(headers) end output_headers, data = map_route_function_output(output) rendered_dict = render_200(;headers=output_headers, endpoint=route.endpoint, data=data, html_file=route.html_file) catch e rendered_dict = render_500(;endpoint=route.endpoint, data=e, html_file=route.html_file, request_path=route.path) end # Static case (no headers param passed) else try output = route.action(route.path) output_headers, data = map_route_function_output(output) rendered_dict = render_200(;headers=output_headers, endpoint=route.endpoint, data=data, html_file=route.html_file) catch e rendered_dict = render_500(;endpoint=route.endpoint, data=e, html_file=route.html_file, request_path=route.path) end end return rendered_dict end """ render_200(;headers::Dict{String, String}, endpoint::String, data::OUTPUT_DATA_FORMATS, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Render HTTP 200 response """ function render_200(;headers::Dict{String, String}, endpoint::String, data::OUTPUT_DATA_FORMATS, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} return CoreRenderer.render(;headers=headers, status_code=Int16(200), endpoint=endpoint, data=data, html_file=html_file) end """ render_400(;endpoint::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Render HTTP 400 response No HTML output file required here, as limited to JSON request """ function render_400(;endpoint::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} return CoreRenderer.render(;status_code=Int16(400), endpoint=endpoint, data="Bad Request", html_file="") end """ render_404(;endpoint::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Render HTTP 404 response """ function render_404(;endpoint::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} return CoreRenderer.render(;status_code=Int16(404), endpoint=endpoint, data="Not Found", html_file=Configuration.Settings[:html_base_filename]*".html") end """ render_405(;endpoint::String, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Render HTTP 405 response """ function render_405(;endpoint::String, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} return CoreRenderer.render(;status_code=Int16(405), endpoint=endpoint, data="Method Not Allowed", html_file=html_file) end """ render_500(;endpoint::String, data::String, html_file::String, request_path::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Render HTTP 500 response Only if NOT Prod: output error details to page """ function render_500(;endpoint::String, data::String, html_file::String, request_path::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Logger.log("500 Internal Server Error when rendering url: $request_path") ## Only output error details if NOT Prod ## if Configuration.is_prod() data = "Internal Server Error" else data = "Internal Server Error: " * data end return CoreRenderer.render(;status_code=Int16(500), endpoint=endpoint, data=data, html_file=html_file) end """ render(;request_headers::Array, request_method::String, request_path::String, request_payload::String) :: String Main entry point of HTTP Rendering - Invalid method will render 405 response - If error during process, render 500 response Check Headers if was JSON request, to return 404 as JSON output """ function render(;request_headers::Dict{String, String}, request_method::String, request_path::String, request_payload::String) ::String rendered_dict::Dict{Symbol, Union{Dict{String, String}, Int16, String}} = Dict() request_route_segments::Array{String, 1} = [] function _render_404_from_content_type(request_headers::Dict{String, String}) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} ## Check Headers if was JSON request, to return 404 in JSON format ## content_type::String = "" endpoint::String = Router.EP_HTML try if haskey(request_headers, "Content-Type") content_type = request_headers["Content-Type"] end if content_type=="application/json" endpoint = Router.EP_JSON end catch e nothing end return render_404(;endpoint=endpoint) end route::Union{Router.Route, Nothing} = Router.get_route(request_path) if isa(route, Router.Route) try ## Check if method allowed ## if request_method == Router.OPTIONS headers_dict::Dict{String, String} = Dict( "Allow" => route.method, "Access-Control-Allow-Methods" => route.method, "Access-Control-Allow-Headers" => "X-PINGOTHER, Content-Type" ) rendered_dict = render_200(;headers=headers_dict, endpoint=route.endpoint, data=Dict(), html_file="") else if request_method==route.method if route.has_regex request_route_segments = URIUtils.get_path_param_segments(;request_path=request_path, route_path=route.path) end rendered_dict = process_backend_function(;route=route, route_segments=request_route_segments, payload=request_payload, headers=request_headers) else rendered_dict = render_405(;endpoint=route.endpoint, html_file=route.html_file) end end catch e rendered_dict = render_500(;endpoint=route.endpoint, data=string(e), html_file=route.html_file, request_path=route.path) end else rendered_dict = _render_404_from_content_type(request_headers) end # Remove empty pair from Header dict (CoreRenderer default) if haskey(rendered_dict[:headers], "") delete!(rendered_dict[:headers], "") end ## Automaticlly set `Content-Type` Header ## rendered_dict[:headers]["Content-Type"] = rendered_dict[:content_type] rendered_dict[:headers]["Content-Length"] = string(sizeof(rendered_dict[:body])) return respond(; headers=rendered_dict[:headers], status_code=rendered_dict[:status_code], body=rendered_dict[:body] ) end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
876
import Flamenco """ close_server() Stop Flamenco server """ function close_server() Flamenco.close_server() end """ respond(; headers::Dict{String, String}, status_code::Int16, body::String) :: String Return response for specified parameters """ respond(; headers::Dict{String, String}, status_code::Int16, body::String) = Flamenco.write_response(status_code, headers; body=body) """ start_server(server_host::String, server_port::Int64) :: Nothing Start Flamenco server and listen for incoming requests and return HTML or JSON body """ function start_server(server_host::String, server_port::Int64) :: Nothing Flamenco.start_server(server_host, server_port) do request::Flamenco.Server.Request render(; request_headers=request.headers, request_method=request.method, request_path=request.target, request_payload=request.body) end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1244
module CoreRenderer import DataFrames import Dance.HTMLRenderer import Dance.JSONRenderer import Dance.StaticRenderer import Dance.Router """ render(;headers::Dict{String, String}=Dict("" => ""), status_code::Int16, endpoint::String, data::Union{DataFrames.DataFrame, Dict, String}, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Generic web output rendering function Depending on `endpoint` field, render JSON or HTML string Cannot set `headers type to `Dict{String, String} here, as can be blank (status_code !=200) """ function render(;headers::Dict{String, String}=Dict("" => ""), status_code::Int16, endpoint::String, data::Union{DataFrames.DataFrame, Dict, String}, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} if endpoint==Router.EP_HTML HTMLRenderer.render(;headers=headers, status_code=status_code, data=data, html_file=html_file) elseif endpoint==Router.EP_JSON if isa(data, String) data::Dict = Dict(:error => data) end JSONRenderer.render(;headers=headers, status_code=status_code, data=data) else StaticRenderer.render(;headers=headers, status_code=status_code, data=data) end end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1644
module HTMLRenderer import DataFrames import JSON3 import Dance.Configuration import Dance.Logger import Dance.PayloadUtils """ populate(;html_file::String="", data::Union{DataFrames.DataFrame, Dict, String}) Populate supplied HTML with data, by replacing `@data` param """ function populate(;html_file::String="", data::Union{DataFrames.DataFrame, Dict, String}) :: String output_data::String = "" if isa(data, DataFrames.DataFrame) output_data = JSON3.write(PayloadUtils.convert_dataframe_to_array(data)) elseif isa(data, Dict) output_data = JSON3.write(data) else output_data = data end html_output::String = read(html_file, String) html_output = replace(html_output, "@data" => output_data) return html_output end """ render(;headers::Dict{String, String}, status_code::Int16, data::Union{DataFrames.DataFrame, Dict, String}, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} HTML renderer `status code` is pre-supplied Cannot set `headers type to `Dict{String, String} here, as can be blank (status_code !=200) """ function render(;headers::Dict{String, String}, status_code::Int16, data::Union{DataFrames.DataFrame, Dict, String}, html_file::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} if status_code==500 Logger.log("500 Internal Server Error when rendering page with $data") end return Dict( :headers => headers, :status_code => status_code, :content_type => "text/html; charset=UTF-8", :body => populate(;html_file=html_file, data=data) ) end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
2282
module JSONRenderer import DataFrames import JSON3 import Dance.Configuration import Dance.Logger import Dance.PayloadUtils const HTTP_STATUS_UNAUTHORIZED = "Unauthorized" const HTTP_STATUS_PAYMENT_REQUIRED = "Payment Required" const HTTP_STATUS_FORBIDDEN = "Forbidden" const HTTP_STATUS_REQUEST_TIMEOUT = "Request Timeout" const HTTP_STATUS_ERROR_CODES = Dict{String, Int16}( HTTP_STATUS_UNAUTHORIZED => 401, HTTP_STATUS_PAYMENT_REQUIRED => 402, HTTP_STATUS_FORBIDDEN => 403, HTTP_STATUS_REQUEST_TIMEOUT => 408 ) """ render(;headers::Dict{String, String}, status_code::Int16, data::Union{DataFrames.DataFrame, Dict}) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Output JSON renderer Though `status code` is pre-supplied, can become 500 Cannot set `headers type to `Dict{String, String} here, as can be blank (status_code !=200) """ function render(;headers::Dict{String, String}, status_code::Int16, data::Union{DataFrames.DataFrame, Dict}) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} body::Union{Array{Any,1}, Dict} = Dict() # One of HTTP_STATUS_ERROR_CODES is supplied as data{Dict} if status_code==200 && isa(data, Dict) if length(data)==1 && :error in keys(data) try status_code = HTTP_STATUS_ERROR_CODES[data[:error]] body = Dict( :error => string(status_code, ": ", data[:error]) ) catch e status_code = 500 body = Dict( :error => "500: Internal Server Error" ) data_string::String = string(data) Logger.log("500 Internal Server Error when rendering page with $data_string: $e") end else body = data end else if isa(data, DataFrames.DataFrame) body = PayloadUtils.convert_dataframe_to_array(data) else body = data end end headers["Access-Control-Allow-Origin"] = Configuration.Settings[:api_access_control_allow_origin] return Dict( :headers => headers, :status_code => status_code, :content_type => "application/json", :body => JSON3.write(body) ) end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
615
module StaticRenderer """ render(;headers::Dict{String, String}, status_code::Int16, data::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} Renderer to output static file as string Cannot set `headers type to `Dict{String, String} here, as can be blank (status_code !=200) """ function render(;headers::Dict{String, String}, status_code::Int16, data::String) :: Dict{Symbol, Union{Dict{String, String}, Int16, String}} return Dict( :headers => headers, :status_code => status_code, :content_type => headers["Content-Type"], :body => data ) end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
858
module PayloadUtils import DataFrames import JSON3 """ convert_array_to_dataframe(array::Array{Any,1}) Convert Array{Any,1} to DataFrame """ function convert_array_to_dataframe(array::JSON3.Array) :: DataFrames.DataFrame df::DataFrames.DataFrame = DataFrames.DataFrame() namelist::Array = Symbol.(array[1]) for (i, name) in enumerate(namelist) df[!, name] = [array[j][i] for j in 2:length(array)] end return df end """ convert_dataframe_to_array(df::DataFrames.DataFrame) Convert DataFrame to Dict{Array}, including column names via first line of array """ function convert_dataframe_to_array(df::DataFrames.DataFrame) :: Array{Any,1} array::Array{Any, 1} = [] push!(array, names(df)) for row in eachrow(df) push!(array, [row[name] for name in names(df)]) end return array end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1068
module URIUtils const ROUTE_REGEX_BASIC_STRUCTURE = r"\/(\(\?<)?[^\/\>\)]+(\>)?([^\/]+(\\\/)?[^\/]+)" const ROUTE_REGEX_PARAM_ONLY = r"(<[^\/(?)]+)+" """ get_path_segments(path::String) Array from breaking path at slashes """ function get_path_segments(path::String) :: Array{String, 1} path_segments::Array{String, 1} = split(path, "/") return filter!(e->e≠"", path_segments) end """ get_path_param_segments(;request_path::String, route_path::String) Parse route.path and match param sections with corresponding request path segments """ function get_path_param_segments(;request_path::String, route_path::String) :: Array{String, 1} request_path_param_segments::Array{String, 1} = [] request_path_segments::Array{String, 1} = get_path_segments(request_path) for (idx, item) in enumerate(collect(eachmatch(ROUTE_REGEX_BASIC_STRUCTURE, route_path))) if endswith(item.match, ")") push!(request_path_param_segments, request_path_segments[idx]) end end return request_path_param_segments end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1040
import Dance include("./utils/main.jl") Dance.start_project("demo") project_settings() routes("html") ## Test all routes with pending slash, to ensure is removed ## @testset "HTTP.listen" begin @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(1) make_and_test_request_get("/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, false, "Hello World") # Test decimal url param make_and_test_request_get("/dict/12.3/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 216, true, Dict("a" => 12.3)) # Test int and string url params make_and_test_request_get("/dict/abc/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, true, Dict("abc" => 123)) make_and_test_request_get( "/dataframe/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 249, true, [ ["A", "B"], [1, "M"], [2, "F"], [3, "F"], [4, "M"] ] ) end delete_project()
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1540
import Dance include("./utils/main.jl") Dance.start_project("demo") project_settings() routes("json") ## Test all routes with pending slash, to ensure is removed ## @testset "HTTP.listen" begin @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(1) make_and_test_request_get("/dict/", 200, Dict("Content-Type" => "application/json"), 9, true, Dict("a" => 123)) make_and_test_request_get( "/dataframe/", 200, Dict("Content-Type" => "application/json"), 43, true, [ ["A", "B"], [1, "M"], [2, "F"], [3, "F"], [4, "M"] ] ) # Test int url param # Test using OPTIONS method before POST (see https://github.com/axios/axios/issues/475) make_and_test_request_options("/post/dict/12") make_and_test_request_post("/post/dict/12", Dict("b" => "abc"), 200, Dict("Content-Type" => "application/json"), 8, true, Dict("b" => 12)) # Test setting Header value in backend # Test accented character, for correct UTF-8 length make_and_test_request_post( "/post/dataframe/", [ ["A", "B"], [1, "M"], [2, "F"], [3, "G"], [4, "ñ"] ], 200, Dict("Content-Type" => "application/json", "foo" => "bar"), 44, true, [ ["A", "B"], [1, "M"], [2, "F"], [3, "G"], [4, "ñ"] ] ) end delete_project()
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1387
import Dance include("./utils/main.jl") Dance.start_project("demo") project_settings() routes("regex") ## Test all routes with pending slash, to ensure is removed ## @testset "HTTP.listen" begin @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(1) # Test hyphen make_and_test_request_get("/dict/ab-/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, true, Dict("ab-" => 123)) # Test underscore make_and_test_request_get("/dict/ab_/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, true, Dict("ab_" => 123)) # Test comma make_and_test_request_get("/dict/ab,/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, true, Dict("ab," => 123)) # Test dot make_and_test_request_get("/dict/ab./123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, true, Dict("ab." => 123)) # Test plus symbol make_and_test_request_get("/dict/ab+/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, true, Dict("ab+" => 123)) # Test accent make_and_test_request_get("/dict/abç/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 218, true, Dict("abç" => 123)) # Test escaped make_and_test_request_get("/dict/ab%2F/123/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 219, true, Dict("ab%2F" => 123)) end delete_project()
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
1980
import Dance include("./utils/main.jl") Dance.start_project("demo") project_settings() routes("static") # Create file for static file route mkdir("files") cp("../sample/static/shipping_containers.jpg", "files/image.jpg") # Ensure route paths cannot go higher than project route in directory structure @test_logs (:error, "Route paths cannot go higher than project route in directory structure") include(joinpath(abspath(pwd()), "routes.jl")) lines_array = [] open("routes.jl", "r") do io global lines_array = readlines(io) for (idx, line) in enumerate(lines_array) if line=="route(\"/../files/image.jpg\", output_file_as_string; method=GET, endpoint=STATIC)" global lines_array deleteat!(lines_array, idx) end end end lines_string = "" for line in lines_array global lines_string lines_string = lines_string * line * "\n" end open("routes.jl", "w") do io write(io, lines_string) end Dance.Router.delete_routes!() ## Test all routes with pending slash, to ensure is removed ## @testset "HTTP.listen" begin @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(1) # Favicon make_and_test_request_get("/favicon.ico/", 200, Dict("Content-Type" => "image/x-icon"), 15406, false, read("../../files/html/favicon.ico")) # Single static file make_and_test_request_get("/files/image.jpg/", 200, Dict("Content-Type" => "image/jpeg"), 84668, false, read("files/image.jpg")) # Static dir for item in [ ["shipping_containers.jpg", 84668], ["office/coffee_and_laptop.jpg", 2126200], ["outdoors/scenary/hills_in_mist.jpg", 3181705], ["outdoors/wildlife/goat_and_sheep.jpg", 3175701] ] path::String = item[1] content_length::Int64 = item[2] make_and_test_request_get("/static/$path/", 200, Dict("Content-Type" => "image/jpeg"), content_length, false, read(joinpath("../sample/static", path))) end end delete_project()
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
447
#!/usr/bin/env julia using Test, SafeTestsets @time begin @time @safetestset "New project settings" begin include("settings_test.jl") end @time @safetestset "Routes HTML" begin include("routes_html_test.jl") end @time @safetestset "Routes JSON" begin include("routes_json_test.jl") end @time @safetestset "Routes Regex" begin include("routes_regex_test.jl") end @time @safetestset "Routes Static" begin include("routes_static_test.jl") end end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
2314
import Dance include("./utils/main.jl") function _build_path(sub_dir::String="") :: String path::String = abspath(pwd()) if length(sub_dir) > 0 path = joinpath(abspath(pwd()), sub_dir) end if Sys.iswindows() path = replace(path, "/" => "\\") end return path end # Test project settings check @testset "Settings - Project Settings Check" begin # Default Prod env does not have :server_host & :server_port defined Dance.start_project("demo") @test_logs (:error, "Please set valid server_host value, cannot be blank") (:error, "Please set valid server_port value, cannot be blank") Dance.populate_settings(joinpath(abspath(@__DIR__), "demo")) project_settings() Dance.populate_settings(joinpath(abspath(@__DIR__), "demo")) @test haskey(Dance.Configuration.Settings, :foo) @test Dance.Configuration.Settings[:foo]=="bar" delete_project(false) end # Test LOAD_PATH: single-dir project case @testset "Settings - LOAD_PATH single-dir" begin Dance.start_project("demo") project_settings() dirs_add_single() @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(5) @test abspath(pwd()) * "/" in LOAD_PATH @test _build_path("html") in LOAD_PATH @test _build_path("settings") in LOAD_PATH @test _build_path("code") in LOAD_PATH delete_project(false) end # Test LOAD_PATH: multiple sub-dirs case @testset "Settings - LOAD_PATH multiple sub-dirs" begin Dance.start_project("demo") project_settings() dirs_add_multiple() @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(2) @test abspath(pwd()) * "/" in LOAD_PATH @test _build_path("html") in LOAD_PATH @test _build_path("settings") in LOAD_PATH @test _build_path("code") in LOAD_PATH @test _build_path("code/sub-dir1") in LOAD_PATH @test _build_path("code/sub-dir1/sub-dir2") in LOAD_PATH delete_project(false) end # Test `files/routes.jl` default contents @testset "Settings - default routes contents" begin Dance.start_project("demo") project_settings() @async include(joinpath(abspath(pwd()), "dance.jl")) sleep(1) make_and_test_request_get("/", 200, Dict("Content-Type" => "text/html; charset=UTF-8"), 217, false, "Hello World") delete_project() end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
924
import DataFrames using Dance.Router function df(headers::Dict{String, String}) :: DataFrames.DataFrame return DataFrames.DataFrame(A = 1:4, B = ["M", "F", "F", "M"]) end function dict_1(params_dict::Dict{Symbol, Union{Float64, Int64, String}}, headers::Dict{String, String}) :: Dict{Symbol, Float64} return Dict(:a => params_dict[:value]) end function dict_2(params_dict::Dict{Symbol, Union{Float64, Int64, String}}, headers::Dict{String, String}) :: Dict{Symbol, Int64} return Dict(Symbol(params_dict[:key]) => params_dict[:value]) end function hello(headers::Dict{String, String}) :: String return "Hello World" end route("/", hello; method=GET, endpoint=EP_HTML) route_group(route_prefix="/dict", method=GET, endpoint=EP_HTML, [ (path=r"/(?<value>\d*\.\d*)", action=dict_1) (path=r"/(?<key>\w+)/(?<value>\d{3})", action=dict_2) ]) route("/dataframe", df; method=GET, endpoint=EP_HTML)
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
915
import DataFrames using Dance.Router function get_df(headers::Dict{String, String}) :: DataFrames.DataFrame return DataFrames.DataFrame(A = 1:4, B = ["M", "F", "F", "M"]) end function get_dict(headers::Dict{String, String}) :: Dict{Symbol, Int64} return Dict(:a => 123) end function post_df(df::DataFrames.DataFrame, headers::Dict{String, String}) :: Tuple{DataFrames.DataFrame, Dict{String, String}} return df, Dict("foo" => "bar") end function post_dict(params_dict::Dict{Symbol, Union{Float64, Int64, String}}, dict::Dict, headers::Dict{String, String}) :: Dict{String, Int64} dict_new::Dict{String, Int64} = Dict() for key in keys(dict) dict_new[string(key)] = params_dict[:value] end return dict_new end route("/dict", get_dict; method=GET) route("/dataframe", get_df; method=GET) route(r"/post/dict/(?<value>\d{2})", post_dict) route("/post/dataframe", post_df)
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
344
using Dance.Router function dict(params_dict::Dict{Symbol, Union{Float64, Int64, String}}, headers::Dict{String, String}) :: Dict{String, Int64} return Dict(params_dict[:key] => params_dict[:value]) end route_group(route_prefix="/dict", method=GET, endpoint=EP_HTML, [ (path=r"/(?<key>([^\/(?)]+))/(?<value>\d{3})", action=dict) ])
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
228
using Dance.Router route("/../files/image.jpg", output_file_as_string; method=GET, endpoint=EP_STATIC) route("/files/image.jpg", output_file_as_string; method=GET, endpoint=EP_STATIC) static_dir("/static", "../sample/static")
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
2457
import HTTP import JSON include("./request.jl") function delete_project(server::Bool=true) :: Nothing cd("..") rm("demo", recursive=true) if server Dance.CoreEngine.close_server() end Dance.Router.delete_routes!() nothing end function dirs_add_multiple() :: Nothing mkdir("code") mkdir("node_modules") # test ignores node dir cd("code") # test dir with file & sub-dir touch("file1.jl") mkdir("sub-dir1") # test dir with only sub-dir cd("sub-dir1") mkdir("sub-dir2") # test dir with file cd("sub-dir2") touch("file2.jl") cd("../../..") nothing end function dirs_add_single() :: Nothing mkdir("code") mkdir("node_modules") # test ignores node dir cd("code") # test dir with file & sub-dir touch("file1.jl") cd("..") nothing end function make_and_test_request_get(path::String, status::Int64, headers::Dict{String, String}, content_length::Int64, is_json_body::Bool, body::Any) :: Nothing r = HTTP.request("GET", "http://127.0.0.1:8000$path") parse_and_test_request(r, status, headers, content_length, is_json_body, body) end function make_and_test_request_options(path::String) :: Nothing r = HTTP.request("OPTIONS", "http://127.0.0.1:8000$path") compare_http_header(r.headers, "Allow", "POST") compare_http_header(r.headers, "Access-Control-Allow-Methods", "POST") compare_http_header(r.headers, "Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type") end function make_and_test_request_post(path::String, payload::Union{Array, Dict}, status::Int64, headers::Dict{String, String}, content_length::Int64, is_json_body::Bool, body::Any) :: Nothing r = HTTP.request("POST", "http://127.0.0.1:8000$path", [], JSON.json(payload)) parse_and_test_request(r, status, headers, content_length, is_json_body, body) end function project_settings() :: Nothing ## Add `dev.jl` file with 1 overwrite & 1 new entry ## cd("demo/settings") touch("dev.jl") open("dev.jl", "w") do io write(io, ":dev = true\n") write(io, ":foo = \"bar\"") end open("Global.jl", "a+") do io write(io, "include(\"dev.jl\")") end cd("..") end function routes(file_suffix::String) :: Nothing open("routes.jl", "w") do io_routes open("../sample/routes/" * file_suffix * ".jl") do io_file write(io_routes, io_file) end end nothing end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
code
2319
import Dates import JSON function compare_http_date_header(header_value::String, timestamp_request_completed::Dates.DateTime) :: Nothing header_value_timestamp::Dates.DateTime = Dates.DateTime(split(header_value, " UTC")[1], "e, d u Y H:M:S") @test header_value_timestamp <= timestamp_request_completed nothing end function compare_http_header(headers::Array, key::String, value::String) :: Nothing @test header_get_value(headers::Array, key::String)==value nothing end function header_get_value(headers::Array, key::String) :: String for item in headers if item[1]==key return item[2] end end end function extract_html_body_content(html_body::Array{UInt8,1}) :: String return split( split(String(html_body), "<div id=\"js-dance-json-data\">")[2], "</div>" )[1] end function extract_json_content(json_body::Array{UInt8,1}) :: String return String(json_body) end function parse_and_test_request(r::HTTP.Messages.Response, status::Int64, headers::Dict{String, String}, content_length::Int64, is_json_body::Bool, body::Any) timestamp_request_completed::Dates.DateTime = Dates.now(Dates.UTC) @test r.status==status for (key, value) in headers compare_http_header(r.headers, key, value) end # TODO: fix Windows HTML file longer due to line final char if !Sys.iswindows() compare_http_header(r.headers, "Content-Length", string(content_length)) end if header_get_value(r.headers, "Content-Type")=="application/json" compare_http_header(r.headers, "Access-Control-Allow-Origin", Dance.Configuration.Settings[:api_access_control_allow_origin]) end compare_http_date_header(header_get_value(r.headers, "Date"), timestamp_request_completed) if is_json_body if header_get_value(r.headers, "Content-Type")=="text/html; charset=UTF-8" @test JSON.parse(extract_html_body_content(r.body))==body else @test JSON.parse(extract_json_content(r.body))==body end else if header_get_value(r.headers, "Content-Type")=="text/html; charset=UTF-8" @test extract_html_body_content(r.body)==body else # Static file case @test r.body==body end end nothing end
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
docs
7425
# Dance | **Build Status** | |:------------------------------------------------------:| | [![Build Status](https://travis-ci.com/DanceJL/Dance.jl.svg?branch=master)](https://travis-ci.com/DanceJL/Dance.jl) [![codecov](https://codecov.io/gh/DanceJL/Dance.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/DanceJL/Dance.jl)| ## 1 - Introduction Julia is an excellent backend language ([read more](https://cloud4scieng.org/2018/12/13/julia-distributed-computing-in-the-cloud/)), powering numerous Artificial Intelligence and Big Data applications. However, integrating these results into web output is not the job of a data scientist, nor should it be complicated. That said, the aim of Dance is to facilitate process by allowing output/reception of: - Dict {Symbol, Any} - DataFrame to/from: - JSON API - JavaScript string in HTML page simply by adding rendering function as a parameter, when building route list. That way you can take advantage of powerful frontend JavaScript frameworks, through easy collaboration with frontend developers. Dance can be used as starting base of new project, as well as web layer addition to existing project. --- ## 2 - Installation Package can be installed with Julia's package manager, either by *pressing* ] to get the Pkg REPL mode and doing: ``` pkg> add Dance ``` or by using Pkg functions: ```julia julia> using Pkg; Pkg.add("Dance") ``` Compatibility is with Julia 1.1 upward. ## 3 - Setup Invoke terminal in working directory and: ```julia using Dance start_project("project name") ``` This will create a new directory specified by `project name` parameter and copy necessary files over. Files include: - `dance.jl`: main entry point of Dance to be always called from terminal - `routes.jl`: main routes list file - `settings/Global.jl`: main project settings - `html/base.html`: for HTML outputs this is default template - `html/favicon.ico`: favicon for HTML pages Depending on environment, other files can be included under `settings` directory to overwrite those under `Global.jl`: - One can add other parameters under these settings files, that will be accessible in project by reading from `Main.Settings` dict. ENV has been avoided due to potential leakage security issues. - **Is recommended to use `secrets.jl` file included under `Global.jl` that will not be stored in version control, for sensitive authentication data.** Can be overwritten/moved: - `routes.jl`: move/rename and update `Settings[:routes_filename]` accordingly - `html/base.html`: move/rename and update `Settings[:html_base_filename]` accordingly - `html/favicon.ico`: move/rename and update `Settings[:html_favicon_name]` accordingly **=> Is recommended to overwrite `api_access_control_allow_origin` settings parameter, to limit API access to known hosts.** ## 4 - Routes ### 4.1 - General Routes can be included in main routes file (`routes.jl` by default), as follows: ```julia route(path::Union{Regex, String}, action::Function; method::String=POST, endpoint=EP_JSON, html_file::String=Configuration.Settings[:html_base_filename]*".html") ``` - Just `path`and `function` are mandatory, *kwargs* can overwrite default values as necessary. That said, note that: - `path` can either be fixed string or contain PCRE regex containing parameter names. - Adding an ending slash (`/`) tp `path` is optional, as incoming requests will have pending slash stripped. Please see: - [Common Parameters](docs/routes/common_parameters.md) - [JSON Endpoints](docs/routes/endoints_json.md) - [HTML Endpoints](docs/routes/endpoints_html.md) for all cases. ### 4.2 - Groups For Common Parameter Routes If some routes share same path prefix or if you want to avoid repeating kwarg parameters, routes can be grouped into route groups as follows: ```julia route_group(route_prefix="/dict", method=GET, endpoint=EP_HTML, [ (path=r"/(?<value>\d.)", action=dict_1) (path=r"/(?<key>\w+)/(?<value>\d{3})", action=dict_2, html_file="html/file") ]) ``` After specifying the common kwargs for routes in question, routes are passed as array of named tuples. As for common kwargs, only set named tuple keys that are necessary to overwrite. ### 4.3 - Static Files Dance can also serve static files. Recommended method is to specify a static directory whose structure will be parsed when building routes for each of the directory's contents. For example all contents of `files` directory will be accessible under `static` path: ```julia static_dir("/static", "files") ``` If you have some other files that you would like to add individually, one can do so by passing path parameter as relative to project's root directory. For instance if you have `image.jpg` in `files` relative to project root: ```julia route("/files/image.jpg", output_file_as_string; method=GET, endpoint=EP_STATIC) ``` ## 5 - Launching Calling: ``` julia dance.jl ``` will start Dance as web server. Press `ctrl` + `C` to stop. By calling: ``` julia dance.jl repl ``` one can enter the REPL mode after project environment has been loaded. Press `ctrl` + `d` to exit. ## 6 - Module Loading & Custom Startup Script Note that when launching, Dance will add the current dir, as well as all sub-directories as module import path. By `static_dir` as defined in `routes.jl` will be ignored during the procedure, as described under `STEP 1` of `dance.jl` file. Should you require ignoring other directories for startup performance optimisation, please populate `ignore_dirs` under `STEP 1`. As outlined under `STEP 3` of `dance.jl` file, any custom scripts can be added, that will be run before Dance launches server/REPL. ## 7 - Security ### 7.1 - Incoming HTTP Headers **Never blindly trust an incoming HTTP request!** As all route functions receive incoming HTTP Headers, it is recommend when necessary to at least verify the `Host` and `X-Forwarded-Host` values. This is not included by default, in order to optimise performance, but here below a sample code, should you like to implement this extra security. ```julia function valid_host() :: Bool allowed_hosts::Array{String, 1} = [Main.Settings[:server_host]] valid_forwarded_host::Bool = false valid_host::Bool = false if "127.0.0.1" in allowed_hosts push!(allowed_hosts, "localhost") end if !(Main.Settings[:server_port] in [80, 443]) for (idx, item) in enumerate(allowed_hosts) allowed_hosts[idx] = item * ":" * string(Main.Settings[:server_port]) end end for pair in request_headers if pair.first=="Host" valid_host = pair.second in allowed_hosts end if pair.first=="X-Forwarded-Host" valid_forwarded_host = pair.second in allowed_hosts end end return valid_host && valid_forwarded_host end ``` ## 8 - Running Dance Under Multi-processing Environment Dance can be run in multi-process environment via Julia Distributed package. This is also particularly useful should you be planning on using cluster of machines in order to implement load balancer. **That said please only use this feature should your website expect heavy traffic or output functions be resource intensive, as else performance will degrade as spawning and data transfer between processes are expensive operations.** To do so edit the upper part of `dance.jl` as indicated in the file.
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
docs
2152
# Common Parameters ## 1 - Input Parameters Dance being a web framework, routes can of course contain parameters. Format must follow PCRE regex containing parameter names. Example routes can be: ```julia function dict_1(params_dict::Dict{Symbol, Int64}, headers::Dict{String, String}) :: Dict{Symbol, Int64} return Dict(:a => params_dict[:value]) end function dict_2(params_dict::Dict{Symbol, Union{Float64, String}}, headers::Dict{String, String}) :: Dict{Symbol, Float64} return Dict(Symbol(params_dict[:key]) => params_dict[:value]) end function post_dict(params_dict::Dict{Symbol, Int64}, dict::Dict, headers::Dict{String, String}) :: Dict{Symbol, Int64} for key in keys(dict) dict[key] = params_dict[:value] end return dict end route(r"/dict/(?<value>\d.)", dict_1; method=GET, endpoint=EP_HTML) route(r"/dict/(?<key>\w+)/(?<value>\d*\.\d*)", dict_2; method=GET, endpoint=EP_HTML) route(r"/post/dict/(?<value>\d{3})", post_2) ``` As you can see are supported: - decimals - integers - strings **Note that**: - Function routes params dict is **first input parameter, in case of Regex type route.** If non-Regex, this parameter is not passed. - If HTTP POST body is supplied (for HTTP GET this parameter is not passed), this will be next parameter. Format is subset of **Dict{Symbol, Union{Float64, Int64, String}}** or **DataFrames.DataFrame**. That is depending on whether **JSON dict or array** was sent via request. - Format of received HTTP Headers is **Dict{String, String}**. **This last parameter must always be supplied to function**. ## 2 - Optional HTTP Header One can set additional HTTP headers for both HTML and JSON API endpoints. To do so simply add the desired headers as second output parameter of the function linked to route in question. **Format must be `Dict{String, String}`**. ```julia import DataFrames using Dance.Router function post_df(df::DataFrames.DataFrame, headers::Dict{String, String}) :: Tuple{DataFrames.DataFrame, Dict{String, String}} return df, Dict("foo" => "bar") end route("/dataframe", post_df) ``` This will set `foo` HTTP header to value of `bar`.
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
docs
2684
# JSON Endpoints Dance serves as JSON API for both GET and POST requests. For GET requests, Julia Dicts and DataFrames are converted on the go to JSON Dicts and Lists. For POST requests reverse conversion occurs. ## 1 - GET Endpoint For API GET endpoints, covering both Dict and DataFrame output cases, `routes.jl` can be similar to below: ```julia import DataFrames using Dance.Router function get_df(headers::Dict{String, String}) :: DataFrames.DataFrame return DataFrames.DataFrame(A = 1:4, B = ["A", "B", "C", "D"]) end function get_dict(headers::Dict{String, String}) :: Dict{Symbol, Int64} return Dict(:a => 123) end route("/dict", get_dict; method=GET) route("/dataframe", get_df; method=GET) ``` Note that `method=GET` had to be specified, as default is `POST`. JSON output for both routes, will become: ```json {"a":123} ``` ```json [ ["A","B"], [1,"A"], [2,"B"], [3,"C"], [4,"D"] ] ``` ## 2 - POST Endpoint For API POST endpoints, covering both Dict and DataFrame output cases, `routes.jl` can be similar to below: ```julia import DataFrames using Dance.Router function post_df(df::DataFrames.DataFrame, headers::Dict{String, String}) :: DataFrames.DataFrame return df end function post_dict(dict::Dict, headers::Dict{String, String}) :: Dict{String, Any} return dict end route("/dict", post_dict) route("/dataframe", post_df) ``` Above examples will output same data as received. For following JSON inputs: ```json [ ["A","B"], [1,"A"], [2,"B"], [3,"C"], [4,"D"] ] ``` ```json {"a":123} ``` Data converted to Julia will be: ```julia 4×2 DataFrames.DataFrame │ Row │ A │ B │ │ │ Int64 │ String │ ├─────┼───────┼────────┤ │ 1 │ 1 │ A │ │ 2 │ 2 │ B │ │ 3 │ 3 │ C │ │ 4 │ 4 │ D │ ``` ```julia Dict{String,Any}("a" => 123) ``` ## 3 - Pre-defined HTTP Status Codes Additionally to facilitate API development, a few standard HTTP response types can easily be integrated. By importing `JSONRenderer`, a return such as: ```julia using Dance.Router import Dance.JSONRenderer function post_dict(dict::Dict, headers::Dict{String, String}) :: Dict{Symbol, String} return Dict(:error => JSONRenderer.HTTP_STATUS_UNAUTHORIZED) end route("/dict", post_dict) ``` is possible. This will automatically set HTTP status code to 401. Currently, possibilities are: ```julia HTTP_STATUS_UNAUTHORIZED = "Unauthorized" HTTP_STATUS_PAYMENT_REQUIRED = "Payment Required" HTTP_STATUS_FORBIDDEN = "Forbidden" HTTP_STATUS_REQUEST_TIMEOUT = "Request Timeout" ``` **CAREFUL when creating the function return dicts, as `:error` key is reserved for this use case**
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.2.4
42a8fe007b4e6cf8c025abc145bf27da7b0928e4
docs
2177
# HTML Endpoints Dance serves HTML GET request outputs. For GET requests, Julia Dicts and DataFrames are converted on the go to JSON Dicts, while Lists to JSON objects. Normal HTML strings can also be outputted. More precisely, `<div id="js-dance-json-data">` HTML tag is where the JSON string/HTML output can be found. ## 1 - Outputs Covering both String, Dict and DataFrame output cases, `routes.jl` can be similar to below: ```julia import DataFrames using Dance.Router function get_string(headers::Dict{String, String}) :: String return "Hello World" end function get_df(headers::Dict{String, String}) :: DataFrames.DataFrame return DataFrames.DataFrame(A = 1:4, B = ["A", "B", "C", "D"]) end function get_dict(headers::Dict{String, String}) :: Dict{Symbol, Int64} return Dict(:a => 123) end route("/", get_string; method=GET, endpoint=EP_HTML) route("/dict", get_dict; method=GET, endpoint=EP_HTML) route("/dataframe", get_df; method=GET, endpoint=EP_HTML) ``` - Note that `method=GET` and `endpoint=EP_HTML` have to be specified, as default is `POST` and `JSON` respectively. - **`html_file` is only should you decide to use different HTML template than default one specified in settings.** - To parse the JSON string under `<div id="js-dance-json-data">` HTML tag, one has to do so via JavaScript script. For instance with jQuery, one would use `jQuery.parseJSON()` function. HTML output for above routes, will become: ```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title></title> </head> <body> <div id="js-dance-json-data">Hello World</div> </body> </html> ``` ```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title></title> </head> <body> <div id="js-dance-json-data">{"a":123}</div> </body> </html> ``` ```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title></title> </head> <body> <div id="js-dance-json-data">[["A","B"],[1,"A"],[2,"B"],[3,"C"],[4,"D"]]</div> </body> </html> ```
Dance
https://github.com/DanceJL/Dance.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
1115
using SparseSensors using LinearAlgebra using Gadfly using DataFrames #Setup the experiment r = 11; # Number of basis modes n = 1000; x = collect(0.0:1/n:1.0); vde_basis = VandermondeBasis(x,r); Ψ = vde_basis.Ψ; #Get the vandermonde basis matrix from the Basis struct #Make design matrix X = copy(transpose(Ψ)); n_samples,n_features = size(X); #Setup QR pivot sensor placement algorithm qr_pivot = QRPivot(X); fit(qr_pivot); pivots = qr_pivot.pivots; #Select the top 15 sensor locations f = abs.(x.^2 .- 0.5); selected_sensors = get_sensors(pivots,15); x_sensed = x[selected_sensors]; y_sensed = f[selected_sensors]; #Ground truth df_true = DataFrame(); df_true[!,"x_true"] = x df_true[!,"y_true"] = f #Sensed df = DataFrame() df[!,"x_sensed"] = x_sensed; df[!,"y_sensed"] = y_sensed; #Plot the results p1 = plot(df, layer(x=:x_sensed,y=:y_sensed,color=["Optimized Sensors"]), layer(df_true,x=:x_true,y=:y_true,Geom.line,Geom.point,color=["True Function"]), Guide.xlabel("x"),Guide.ylabel("y"), Theme(background_color=colorant"white")) #Save image draw(SVG("example.svg",7inch,3.326inch),p1)
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
503
module SparseSensors using LinearAlgebra: Matrix, conj greet() = print("Hello World!") using LinearAlgebra include("qr.jl") include("ccqr.jl") include("basis.jl") include("reconstruct.jl") export QRPivot,CostQRPivot,fit,VandermondeBasis export get_sensors function get_sensors(sampler) return sampler.pivots end function get_sensors(pivots::AbstractArray,n_sensors::Int) return pivots[1:n_sensors] end function get_sensors(sampler,n_sensors) return sampler.pivots[1:n_sensors] end end
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
666
struct Basis Ψ::Matrix r::Int end function VandermondeBasis(x,r::Int;verbose::Bool=false) """Makes a vandermonde basis given a range and a number of basis modes""" Ψ = zeros((length(x),r)) for (j,col) in enumerate(eachcol(Ψ)) ψ = make_vander_column(j,x) if verbose println("ψ","_"*string(j)," size: ",size(ψ)) end Ψ[:,j] = make_vander_column(j,x) #Each col is x^(k-1) end if verbose print("Final Ψ size: ",size(Ψ)) end return Basis(Ψ,r) #Truncated basis matrix end function make_vander_column(k,col_k) ψ = [x^(k-1) for x in col_k] return ψ #Column of basis matrix end
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
1758
### # Const-constrained QR optimizer for sensor placement. ### mutable struct CostQRPivot Ψ::AbstractArray pivots::AbstractArray sensor_costs::AbstractArray #Costs/weights associated with each sensor. Postsive is bad, negative good. end function CostQRPivot(qrpivot::QRPivot,sensor_costs::Vector{Float64}) return CostQRPivot(qrpivot.Ψ,qrpivot.pivots,sensor_costs) end function CostQRPivot(Ψ::AbstractArray,pivots::Vector,sensor_costs::Vector{Float64}) return CostQRPivot(Ψ,pivots,sensor_costs) end function fit(cost_qr_pivot::CostQRPivot) n,m = size(cost_qr_pivot.Ψ) if cost_qr_pivot.sensor_costs !== n throw(DomainError(cost_qr_pivot.sensor_costs,"The specified sensor costs are inconsistent with the basis dimensions")) end #Initialize helper variables R,p,k = make_helper_variables(cost_qr_pivot.Ψ) for j in 1:k u,i_piv = qr_reflector(R[j:n,j:m],cost_qr_pivot.sensor_costs) #Track column pivots i_piv += j p[[j,i_piv]] = p[[i_piv,j]] #Switch column R[:,[j,i_piv]] = R[:,[i_piv,j]] #Apply reflector R[j:n,j:m] -= outer(u,dot(u,R[j:n,j:m])) R[j+1:n,j] = 0 end cost_qr_pivot.pivots = p end function make_helper_variables(Ψ) """Constructs the reflector helper variables""" R = conj(Ψ) p = [i for i in 1:n] k = min(m,n) return R,p,k end function qr_reflector(r,costs) dlens = sqrt(sum(abs(eachrow(r))^2)) #Norm of each column i_piv = argmax(dlens-costs) # choose pivot dlen = dlens[i_piv] if dlen > 0 u = r[:,i_piv]/dlen u[1] += sign(u[1])+(u[1]==0) u/=sqrt(abs(u[1])) else u = r[:,i_piv] u[1] = sqrt(2) end return u,i_piv end
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
867
### # Standard QR Pivot Optimizer ### mutable struct QRPivot Ψ::AbstractArray #Basis matrix from SVD, RPCA, etc. pivots::AbstractArray #Ranked list of sensor locations end function QRPivot(Ψ) n,m = size(Ψ) pivots = zeros((max(n,m),1)) return QRPivot(Ψ,pivots) end function QRPivot(Ψ,n_sensors::Int) n,m = size(Ψ) pivots = zeros((n_sensors,1)) return QRPivot(Ψ,pivots) end function QRPivot(Ψ,pivots::AbstractArray) return QRPivot(Ψ,pivots) end function fit(qr_pivot::QRPivot;optimizer_kwargs...) """ Fits the QRPivot sensor placement. qrpivot::QRPivot QRPivot object. optimizer_kwargs: dictionary Optional settings for optimizer """ qr_pivot.pivots = sensor_placement(qr_pivot.Ψ) end function sensor_placement(Ψ) # --> Compute the QRPivot w/ column pivoting decomposition of Ψ. _, _, p = qr(conj(Ψ), Val(true)) return p[1:size(Ψ, 2)] end
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
940
using Convex,SCS mutable struct SSPOR basis::Basis selected_sensors::Vector n_sensors::Int n_basis_modes::Int fit_::Function predict_::Function optimizer end struct Reconstructor fit::Function predict::Function end # function fit(model::SSPOR;quiet=true) # if model.fit_ === fit_lsq # model.fit_() # end # end # function predict(model::SSPOR,x::Vector;quiet=true) # if model.predict_ === predict_lsq # model.predict_(model.Ψ,x,model.n_basis_modes) # end # end function fit_lsq(Ψ,x,y,selected_sensors) y_sensed = y[selected_sensors]; x_sensed = x[selected_sensors]; Ψ_sensed = Ψ[:,selected_sensors] return Ψ_sensed,x_sensed,y_sensed end function predict_lsq(Ψ,x,y,n_basis_modes) X = Convex.Variable(size(x)) prob = minimize(sumsquares(y-Ψ*X)) solve!(prob,()-> SCS.Optimizer(verbose=false)) prob.status return prob.optval end
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
code
99
using SparseSensors using Test @testset "SparseSensors.jl" begin # Write your tests here. end
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
0.0.1
6d3894ef4e4c1e1c740551745b2d6fd749d78903
docs
3013
# SparseSensors.jl This repository is an implementation of the core sparse sensor placement with QR factorization and cost-constrained QR factorization algorithms from Manohar, _et al.,_ "Data-Driven Sparse Sensor Placcement for Reconstruction", and other papers, in Julia. This is a hobbyist port of the fantastic Python library [pysensors](https://github.com/dynamicslab/pysensors) in Julia. All collaborations and contributions are welcome. ## Installation To install, use Pkg. From the Julia REPL, press ] to enter Pkg-mode and run ```julia pkg> add SparseSensors ``` ## Example ```julia using SparseSensors using LinearAlgebra using Gadfly using DataFrames #Setup the experiment r = 11; # Number of basis modes n = 1000; x = collect(0.0:1/n:1.0); vde_basis = VandermondeBasis(x,r); Ψ = vde_basis.Ψ; #Get the vandermonde basis matrix from the Basis struct #Make design matrix X = copy(transpose(Ψ)); n_samples,n_features = size(X); #Setup QR pivot sensor placement algorithm qr_pivot = QRPivot(X); fit(qr_pivot); pivots = qr_pivot.pivots; #Select the top 15 sensor locations f = abs.(x.^2 .- 0.5); selected_sensors = get_sensors(pivots,15); x_sensed = x[selected_sensors]; y_sensed = f[selected_sensors]; #Ground truth df_true = DataFrame(); df_true[!,"x_true"] = x df_true[!,"y_true"] = f #Sensed df = DataFrame() df[!,"x_sensed"] = x_sensed; df[!,"y_sensed"] = y_sensed; #Plot the results p1 = plot(df, layer(x=:x_sensed,y=:y_sensed,color=["Optimized Sensors"]), layer(df_true,x=:x_true,y=:y_true,Geom.line,Geom.point,color=["True Function"]), Guide.xlabel("x"),Guide.ylabel("y")) ``` ![](example.svg) ## Dependencies julia >v1.6. LinearAlgebra, Gadfly and DataFrames for plotting. ## Todo: - Implement high level SSPOR and SSPOC interfaces - Implement high level basis representation wrapper for SVD, etc. - Set up compatibility with JuliaML/MLJ.jl/ScikitLearn.jl References ------------ - Manohar, Krithika, Bingni W. Brunton, J. Nathan Kutz, and Steven L. Brunton. "Data-driven sparse sensor placement for reconstruction: Demonstrating the benefits of exploiting known patterns." IEEE Control Systems Magazine 38, no. 3 (2018): 63-86. `[DOI] <https://doi.org/10.1109/MCS.2018.2810460>` - Clark, Emily, Travis Askham, Steven L. Brunton, and J. Nathan Kutz. "Greedy sensor placement with cost constraints." IEEE Sensors Journal 19, no. 7 (2018): 2642-2656. `[DOI] <https://doi.org/10.1109/JSEN.2018.2887044>` - de Silva, Brian M., Krithika Manohar, Emily Clark, Bingni W. Brunton, Steven L. Brunton, J. Nathan Kutz. "PySensors: A Python package for sparse sensor placement." arXiv preprint arXiv:2102.13476 (2021). `[arXiv] <https://arxiv.org/abs/2102.13476>`
SparseSensors
https://github.com/samtalki/SparseSensors.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
1814
#SP500 dataset, lower bound d = 0, upper bound u =3/32=9.375% # User Guides: https://github.com/PharosAbad/LightenQP.jl/wiki/User-Guides#portfolio-selection-1 using LightenQP using TranscodingStreams, CodecXz, Serialization, Downloads function main() #download the online data xzFile = joinpath(tempdir(),"sp500.jls.xz") #xzFile = "/tmp/sp500.jls.xz" if !isfile(xzFile) Downloads.download("https://github.com/PharosAbad/PharosAbad.github.io/raw/master/files/sp500.jls.xz", xzFile) end io = open(xzFile) io = TranscodingStream(XzDecompressor(), io) E = deserialize(io) V = deserialize(io) close(io) N = length(E) u = fill(3 / 32, N) #= Q = OOQP(V, zeros(N), u) ts = @elapsed x, status = solveOOQP(Q) println("--- LightenQP Method @LVEP (Lowest Variance Efficient Portfolio, also called GMVP, Global Minimum Variance Portfolio): ", ts, " seconds") Q1 = OOQP(V, -E, u) ts = @elapsed x1, status1 = solveOOQP(Q1) println("--- LightenQP Method @L=1: ", ts, " seconds") =# #v1.0.1 Q = OOQP(V, E, u) ts = @elapsed xH, statusH = fPortfolio(Q, Inf) #HMFP (Highest Mean Frontier Portfolio) println("HMEP (Highest Mean Efficient Portfolio) --- fPortfolio @ max mu: ", ts, " seconds") ts = @elapsed xL, statusL = fPortfolio(Q, -Inf) #LMFP (Lowest Mean Frontier Portfolio) println("LMEP (Lowest Mean Efficient Portfolio) --- fPortfolio @ min mu: ", ts, " seconds") ts = @elapsed x0, status0 = fPortfolio(Q, 0.0) println("LMEP (Lowest Mean Efficient Portfolio, also called GMVP, Global Minimum Variance Portfolio) --- fPortfolio @ L=0: ", ts, " seconds") ts = @elapsed x2, status2 = fPortfolio(Q, 2.0) println(" --- fPortfolio @ L=2.0: ", ts, " seconds") end main() nothing
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
12068
#Speed and Accuracy: Quadratic pragramming #compare: LightenQP, OSQP, Clarabel using EfficientFrontier, LinearAlgebra using TranscodingStreams, CodecXz, Serialization, Downloads using LightenQP: LightenQP #, solveOOQP import LightenQP: OOQP, fPortfolio using Statistics if length(filter((x) -> x == :uOSQP, names(Main, imported=true))) == 0 include("./uOSQP.jl") using .uOSQP end if length(filter((x) -> x == :uClarabel, names(Main, imported=true))) == 0 include("./uClarabel.jl") using .uClarabel end function OOQP(P::Problem{T}) where {T} #Pack P into OOQP (; E, V, u, d, G, g, A, b, N, M, J) = P iu = findall(u .< Inf) C = [G; -Matrix{T}(I, N, N); Matrix{T}(I, N, N)[iu, :]] gq = [g; -d; u[iu]] L = J + N + length(iu) OOQP{T}(V, A, C, E, b, gq, N, M, L) end #= function fPortfolio(P::Problem{T}, L::T=0.0; settings=LightenQP.Settings{T}()) where {T} Q = OOQP(P) fPortfolio(Q, L; settings=settings) end function fPortfolio(mu::T, P::Problem{T}; settings=LightenQP.Settings{T}(), check=true) where {T} Q = OOQP(P) fPortfolio(mu, Q; settings=settings, check=check) end =# function testData(ds::Symbol) if ds == :Ungil E, V = EfficientFrontier.EVdata(:Ungil, false) A = [1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0] b = [1.0; 0.25] G = [0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0] G[1, :] = -G[1, :] g = [-0.3; 0.6] d = vec([-0.0 -0.0 -0.0 -0.0 -0.0 -0.0 -0.0 -0.0 -0.0 -0.0 -0.1 -0.1 -0.1 -0.1]) u = vec([0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.1 0.1 0.1 0.3 0.3 0.3 0.3]) P = Problem(E, V, u, d, G, g, A, b) elseif ds == :SP500 xzFile = joinpath(tempdir(),"sp500.jls.xz") #xzFile = "/tmp/sp500.jls.xz" if !isfile(xzFile) Downloads.download("https://github.com/PharosAbad/PharosAbad.github.io/raw/master/files/sp500.jls.xz", xzFile) end io = open(xzFile) io = TranscodingStream(XzDecompressor(), io) E = deserialize(io) V = deserialize(io) close(io) N = length(E) u = fill(3 / 32, N) pd = true if pd N = 263 ip = 1:N V = V[ip, ip] E = E[ip] u = fill(3 / 32, N) end P = Problem(E, V, u) else error("Unknown dataset") end return P end function SpeedAccuracy(aEF, P, QPsolver, M=16) V = P.V N = length(aEF.mu) - 1 T = zeros(N, M) #time used, for speed A = zeros(N, M) #Accuracy O = zeros(N, M) #Objective function S = trues(N, M) #Solution status check = true for k in 1:N for m = 1:M mu = ((M + 1 - m) * aEF.mu[k] + (m - 1) * aEF.mu[k+1]) / M z = ePortfolio(mu, aEF) if QPsolver == :LightenQP #ts = @elapsed y, status = fPortfolio(mu, P; check=check) ts = @elapsed y, status = fPortfolio(mu, OOQP(P); check=check) check = false st = status > 0 elseif QPsolver == :OSQP ts = @elapsed y = OpSpQP(P, mu) st = y.info.status_val == 1 elseif QPsolver == :Clarabel ts = @elapsed y = ClarabelQP(P, mu) st = Int(y.status) == 1 else error("Unknown QP solver") end S[k, m] = st T[k, m] = ts A[k, m] = norm(y.x - z, Inf) O[k, m] = sqrt(y.x' * V * y.x) - sqrt(z' * V * z) end end return T, A, O, S end function cmpSA(ds::Symbol) P = testData(ds) println("--- Starting EfficientFrontier ---") t0 = time() ts = @elapsed aCL = EfficientFrontier.ECL(P) aEF = eFrontier(aCL, P) t1 = time() println("1st run, EfficientFrontier: ", t1 - t0, " seconds", "\n aCL: ", ts, " seconds") t0 = time() ts = @elapsed aCL = EfficientFrontier.ECL(P) aEF = eFrontier(aCL, P) t1 = time() println("2nd run, EfficientFrontier: ", t1 - t0, " seconds", "\n aCL: ", ts, " seconds") QPsolver = :LightenQP Tl, Al, Ol, Sl = SpeedAccuracy(aEF, P, QPsolver) QPsolver = :OSQP To, Ao, Oo, So = SpeedAccuracy(aEF, P, QPsolver) QPsolver = :Clarabel Tc, Ac, Oc, Sc = SpeedAccuracy(aEF, P, QPsolver) redirect_stdio(stdout="stdout.txt") do #status println("\n------- Solution status ------- LightenQP/OSQP/Clarabel") show(stdout, "text/plain", Sl) println("") show(stdout, "text/plain", So) println("") show(stdout, "text/plain", Sc) println("") #Accuracy println("\n------- Accuracy -------LightenQP/OSQP/Clarabel ", round.([norm(Al, Inf), norm(Ao, Inf), norm(Ac, Inf)], sigdigits=3)) println("---- quantile 99% ---- ", round.([quantile(Al[:], 0.99), quantile(Ao[:], 0.99), quantile(Ac[:], 0.99)], sigdigits=3)) println("------- median ------- ", round.([median(Al[:]), median(Ao[:]), median(Ac[:])], sigdigits=3)) show(stdout, "text/plain", round.(Al, sigdigits=3)) println("") show(stdout, "text/plain", round.(Ao, sigdigits=3)) println("") show(stdout, "text/plain", round.(Ac, sigdigits=3)) println("") #Speed println("\n--- Speed (time span, smaller for faster speed) ---LightenQP/OSQP/Clarabel ", round.([norm(Tl, Inf), norm(To, Inf), norm(Tc, Inf)], sigdigits=3)) println("---- quantile 99% ---- ", round.([quantile(Tl[:], 0.99), quantile(To[:], 0.99), quantile(Tc[:], 0.99)], sigdigits=3)) println("------- median ------- ", round.([median(Tl[:]), median(To[:]), median(Tc[:])], sigdigits=3)) show(stdout, "text/plain", round.(Tl, sigdigits=3)) println("") show(stdout, "text/plain", round.(To, sigdigits=3)) println("") show(stdout, "text/plain", round.(Tc, sigdigits=3)) println("") #Objective function println("\n--- Objective function value (diff in sd, not variance) ---LightenQP/OSQP/Clarabel ", round.([norm(Ol, Inf), norm(Oo, Inf), norm(Oc, Inf)], sigdigits=3)) println("---- quantile 99% ---- ", round.([quantile(Ol[:], 0.99), quantile(Oo[:], 0.99), quantile(Oc[:], 0.99)], sigdigits=3)) println("------- median ------- ", round.([median(Ol[:]), median(Oo[:]), median(Oc[:])], sigdigits=3)) show(stdout, "text/plain", round.(Ol, sigdigits=3)) println("") show(stdout, "text/plain", round.(Oo, sigdigits=3)) println("") show(stdout, "text/plain", round.(Oc, sigdigits=3)) println("") end #redirect_stdio() #return Sl, So, Sc, Al, Ao, Ac, Tl, To, Tc, Ol, Oo, Oc return nothing end function SpeedAccuracyL(aEF, P, aCL, QPsolver, M=16) V = P.V N = length(aEF.mu) - 1 T = zeros(N, M) #time used, for speed A = zeros(N, M) #Accuracy O = zeros(N, M) #Objective function S = trues(N, M) #Solution status for k in 1:N i = aEF.ic[k] t = aCL[i] for m = 1:M #mu = ((M + 1 - m) * aEF.mu[k] + (m - 1) * aEF.mu[k+1]) / M L = ((M + 1 - m) * t.L1 + (m - 1) * t.L0) / M z = ePortfolio(P, L, aCL) if QPsolver == :LightenQP ts = @elapsed y, status = fPortfolio(OOQP(P), L) #fPortfolio(P; L) use active-set numerical solver st = status > 0 elseif QPsolver == :OSQP #ts = @elapsed y = OpSpQP(P, mu) ts = @elapsed y = OpSpQP(P; L) st = y.info.status_val == 1 elseif QPsolver == :Clarabel #ts = @elapsed y = ClarabelQP(P, mu) ts = @elapsed y = ClarabelQP(P; L) st = Int(y.status) == 1 else error("Unknown QP solver") end S[k, m] = st T[k, m] = ts A[k, m] = norm(y.x - z, Inf) O[k, m] = sqrt(y.x' * V * y.x) - sqrt(z' * V * z) end end return T, A, O, S end function cmpSA_L(ds::Symbol) P = testData(ds) println("--- Starting EfficientFrontier ---") t0 = time() ts = @elapsed aCL = EfficientFrontier.ECL(P) aEF = eFrontier(aCL, P) t1 = time() println("1st run, EfficientFrontier: ", t1 - t0, " seconds", "\n aCL: ", ts, " seconds") t0 = time() ts = @elapsed aCL = EfficientFrontier.ECL(P) aEF = eFrontier(aCL, P) t1 = time() println("2nd run, EfficientFrontier: ", t1 - t0, " seconds", "\n aCL: ", ts, " seconds") QPsolver = :LightenQP Tl, Al, Ol, Sl = SpeedAccuracyL(aEF, P, aCL, QPsolver) QPsolver = :OSQP To, Ao, Oo, So = SpeedAccuracyL(aEF, P, aCL, QPsolver) QPsolver = :Clarabel Tc, Ac, Oc, Sc = SpeedAccuracyL(aEF, P, aCL, QPsolver) redirect_stdio(stdout="stdoutL.txt") do #status println("\n------- Solution status ------- LightenQP/OSQP/Clarabel") show(stdout, "text/plain", Sl) println("") show(stdout, "text/plain", So) println("") show(stdout, "text/plain", Sc) println("") #Accuracy println("\n------- Accuracy -------LightenQP/OSQP/Clarabel ", round.([norm(Al, Inf), norm(Ao, Inf), norm(Ac, Inf)], sigdigits=3)) println("---- quantile 99% ---- ", round.([quantile(Al[:], 0.99), quantile(Ao[:], 0.99), quantile(Ac[:], 0.99)], sigdigits=3)) println("------- median ------- ", round.([median(Al[:]), median(Ao[:]), median(Ac[:])], sigdigits=3)) show(stdout, "text/plain", round.(Al, sigdigits=3)) println("") show(stdout, "text/plain", round.(Ao, sigdigits=3)) println("") show(stdout, "text/plain", round.(Ac, sigdigits=3)) println("") #Speed println("\n--- Speed (time span, smaller for faster speed) ---LightenQP/OSQP/Clarabel ", round.([norm(Tl, Inf), norm(To, Inf), norm(Tc, Inf)], sigdigits=3)) println("---- quantile 99% ---- ", round.([quantile(Tl[:], 0.99), quantile(To[:], 0.99), quantile(Tc[:], 0.99)], sigdigits=3)) println("------- median ------- ", round.([median(Tl[:]), median(To[:]), median(Tc[:])], sigdigits=3)) show(stdout, "text/plain", round.(Tl, sigdigits=3)) println("") show(stdout, "text/plain", round.(To, sigdigits=3)) println("") show(stdout, "text/plain", round.(Tc, sigdigits=3)) println("") #Objective function println("\n--- Objective function value (diff in sd, not variance) ---LightenQP/OSQP/Clarabel ", round.([norm(Ol, Inf), norm(Oo, Inf), norm(Oc, Inf)], sigdigits=3)) println("---- quantile 99% ---- ", round.([quantile(Ol[:], 0.99), quantile(Oo[:], 0.99), quantile(Oc[:], 0.99)], sigdigits=3)) println("------- median ------- ", round.([median(Ol[:]), median(Oo[:]), median(Oc[:])], sigdigits=3)) show(stdout, "text/plain", round.(Ol, sigdigits=3)) println("") show(stdout, "text/plain", round.(Oo, sigdigits=3)) println("") show(stdout, "text/plain", round.(Oc, sigdigits=3)) println("") end #redirect_stdio() #return Sl, So, Sc, Al, Ao, Ac, Tl, To, Tc, Ol, Oo, Oc return nothing end #FP(mu=mu0), Az=b contains z′E=μ, objective function L=0 #cmpSA(:Ungil) cmpSA(:SP500) #FP(L=L0), , Az=b excludes z′E=μ, objective function has -L*z′E #cmpSA_L(:Ungil) cmpSA_L(:SP500) nothing #= Remark: * OSQP is dangerous when mu version is computed, low accuracy, volatile speed (fastest near LMEP, but slowest near HMEP, Highest Mean Efficient Portfolio) * OSQP is very good, when L is used. Accuracy 1.28e-10 (SP500 and Ungil), very good (deteriorate near LMEP ); speed 0.0751 (Ungil) and 0.0909 (SP500), fastest, no speed down at HMEP; objective 7.53e-14 (SP500 and Ungil), very good =#
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
1041
#Example: no short-sale with upper bounded for the problem of portfolio selection #= min (1/2)z′Vz -z′μ s.t. z′1=1 , 0≤z≤u =# # User Guides: https://github.com/PharosAbad/LightenQP.jl/wiki/User-Guides#portfolio-selection-1 using LightenQP using LinearAlgebra function main() V = [1/100 1/80 1/100 1/80 1/16 1/40 1/100 1/40 1/25] E = [109 / 100; 23 / 20; 119 / 100] #Q = OOQP(V, -E) #x, status = solveOOQP(Q) u = [0.7; +Inf; 0.7] #Inf means no bounded Q = OOQP(V, -E, u) #OOQP + bounds 0 <= x <= u #settings = Settings() x, status = solveOOQP(Q) #solve by Algorithm MPC (Mehrotra Predictor-Corrector) #v1.0.1 O = OOQP(V, E, u) #y, statusy = fPortfolio(O; L=1.0) y, statusy = fPortfolio(O, 1.0) display(norm(x.x - y.x, Inf)) #0 end #= using EfficientFrontier P = Problem(E, V, u) nS = Settings(P) aCL = EfficientFrontier.ECL(P; numSettings=nS) aEF = eFrontier(aCL, P) mu = x.x'*E z = ePortfolio(mu, aEF) x.x - z =# main() nothing
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
760
"The primal-dual interior point algorithms supplied by OOQP" module LightenQP #= #solving convex quadratic programming (QP) problems in the following form (called by OOQP) min (1/2)x′Vx+q′x s.t. Ax=b Cx≤g https://github.com/emgertz/OOQP OOQP in C/C++ https://github.com/oxfordcontrol/qpip/blob/master/qpip.m solver OOQP, but in a pure matlab implementation =# using LinearAlgebra #using SparseArrays export OOQP #, Settings, Solution export solveOOQP, mpcQP, mpcLP, fPortfolio include("./types.jl") # Algorithm MPC (Mehrotra Predictor-Corrector), Primal-Dual Interior-Point Algorithms include("./MPC.jl") #The general quadratic programming formulation recognized by LightenQP, solved by solveOOQP (Algorithm MPC) include("./mpcQP.jl") end
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
7185
#the solver, Algorithm MPC (Mehrotra Predictor-Corrector) from OOQP """ solveOOQP(Q::OOQP; settings=Settings()) solveOOQP(V, q, A, b, C, g; settings) solving convex quadratic programming problems (QP) in the following form define by Q::OOQP ```math min (1/2)x′Vx+q′x s.t. Ax=b ∈ R^{M} Cx≤g ∈ R^{L} ``` Outputs x::Solution : structure containing the primal solution 'x', dual variables 'y' and 'z' corresponding to the equality and inequality multipliers respectively, and slack variables 's' status::Int : > 0 if successful (=iter_count), 0 if infeasibility detected, < 0 if not converged (=-iter_count) # Example ``` using LightenQP V = [1/100 1/80 1/100 1/80 1/16 1/40 1/100 1/40 1/25] E = [109 / 100; 23 / 20; 119 / 100] u = [0.7; +Inf; 0.7] #Inf means no bounded Q = OOQP(V, -E, u) #OOQP + bounds 0 <= x <= u x, status = solveOOQP(Q) #solve by Algorithm MPC (Mehrotra Predictor-Corrector) ``` See [`Documentation for LightenQP.jl`](https://github.com/PharosAbad/LightenQP.jl/wiki) See also [`OOQP`](@ref), [`Solution`](@ref), [`Settings`](@ref), [`mpcQP`](@ref) """ function solveOOQP(V::Matrix{T}, q::Vector{T}, A::Matrix{T}, b::Vector{T}, C::Matrix{T}, g::Vector{T}; settings=Settings{T}()) where {T} Q = OOQP(V, q; A=A, b=b, C=C, g=g) return solveOOQP(Q; settings=settings) end function solveOOQP(Q::OOQP{T}; settings=Settings{T}()) where {T} #cook up an initial solution Soln = Solution(Q) res = Residuals(Q) J, idxS = initJacobian(Q) normD = dataNorm(Q) #data norm initialize defaultStart!(Soln, res, Q, J, normD) (; z, s) = Soln iter = 1 status = 0 while iter <= settings.maxIter muval = calcMu(Soln) #get the complementarity measure mu calcResiduals!(res, Q, Soln) ##Update the right hand side residuals #termination test status = checkStatus(Q, Soln, res, settings, muval, normD) if status != 0 break end # PREDICTOR STEP find the RHS for this step J[idxS] = -(s ./ z) #updateJacobian F = lu(J) #display((typeof(J),typeof(F))) stepAff = searchDirection(F, Q, Soln, res) alphaAff = stepBound(Soln, stepAff) #determine the largest step that preserves consistency of the multiplier constraint muAff = muStep(Soln, stepAff, alphaAff) sigma = (muAff / muval)^3 #CENTERING-CORRECTOR STEP rSfix!(res, stepAff, -sigma * muval) stepCC = searchDirection(F, Q, Soln, res) alphaMax = stepBound(Soln, stepCC) #determine the largest step that preserves consistency of the multiplier constraint stepSize = alphaMax * settings.scaleStep #use a crude step scaling factor addToSolution!(Soln, stepCC, stepSize) #take the step and update mu iter += 1 end iter = (status == 1) ? iter : ((status == 0) ? -iter : 0) return Soln, iter end function addToSolution!(Soln, step, alpha) #shift the problem variables by a scaled correction term (; x, y, z, s) = Soln x .+= alpha * step.x y .+= alpha * step.y z .+= alpha * step.z s .+= alpha * step.s return nothing end function calcMu(Soln) #calculate complementarity measure (; z, s) = Soln L = length(z) # L==0 no inequalities case mu = L == 0 ? 0.0 : (z' * s) / L return mu end function calcResiduals!(res, Q, Soln) #Calculates the problem residuals based on the current variables (; V, A, C, q, b, g) = Q (; x, y, z, s) = Soln (; rV, rA, rC, rS) = res rV .= V * x - A' * y + C' * z + q # V*x + q - A'*y + C'*z rA .= A * x - b # A*x - b rC .= C * x + s - g # C*x - g + s rS .= z .* s # w = SZ1 return nothing end function checkStatus(Q, Soln, res, settings, muval, normD) #test for convergence or infeasibility gap = abs(dualityGap(Q, Soln)) normR = residualNorm(res) phi = (normR + gap) ./ normD minPhi = min(settings.minPhi, phi) if muval <= settings.tolMu && normR <= settings.tolR * normD status = 1 #convergence elseif (phi > 1e-8 && phi > 1e4 * minPhi) status = -1 #infeasible else status = 0 #not converged end return status end function dataNorm(Q) (; V, A, C, q, b, g) = Q vecData = [V[:]; A[:]; C[:]; q[:]; b[:]; g[:]] #vectorize the data, infinite values have been removed return norm(vecData, Inf) end function defaultStart!(Soln, res, Q, J, normD) (; z, s) = Soln s0 = sqrt(normD) #find some interior point (large z and s) z .= s0 s .= s0 calcResiduals!(res, Q, Soln) F = lu(J) step = searchDirection(F, Q, Soln, res) addToSolution!(Soln, step, 1.0) #take the full affine scaling step z .+= 1e3 #shiftBoundVariables s .+= 1e3 return nothing end function dualityGap(Q, Soln) #Calculate duality gap = x'Vx + q'x - b'y + g'z (; V, q, b, g) = Q (; x, y, z) = Soln return x' * (V * x) + q' * x - b' * y + g' * z end function initJacobian(Q::OOQP{T}) where {T} (; V, A, C, N, M, L) = Q #Create the Jacoban matrix with a dummy Sigma S = -Matrix{T}(I, L, L) Z1 = zeros(T, M, M) Z2 = zeros(T, L, M) #construct the jacobian J = [V A' C' A Z1 Z2' C Z2 S] #get the indices for the entries of S idx = (N + M) .+ (1:L) idxS = Base._sub2ind(size(J), idx, idx) return J, idxS end function muStep(Soln, step, alpha) #calculate the value of z's/L given a step in the proposed z and s directions (; z, s) = Soln dz = step.z * alpha ds = step.s * alpha return ((z + dz)' * (s + ds)) / length(s) end function residualNorm(res) (; rV, rA, rC) = res vec = [rV[:]; rA[:]; rC[:]] return norm(vec, Inf) #residual vector norms end function rSfix!(res, stepAff, shift) #adds to the rS component of the residuals a term = dZ*dS*1 + shift*1 dz = stepAff.z ds = stepAff.s res.rS .+= dz .* ds .+ shift #update the residuals return nothing end function searchDirection(F, Q, Soln, res) #Solve the Newton system for a given set of residuals, using the current Jacobian factorization (; z, s) = Soln (; rV, rA, rC, rS) = res rC1 = rC - (rS ./ z) #eliminate the rS terms rhs = [rV; rA; rC1] #put them all together lhs = F \ rhs #solve it #parse the solution (including any post-solving) back into a *copy* of the variables (; N, M, L) = Q dx = -lhs[1:N] dy = lhs[(1:M).+N] dz = -lhs[(1:L).+(N+M)] #post-solve solve for the ds ds = -(rS + s .* dz) ./ z return Solution(dx, dy, dz, ds) #the output should have the same structure as the Soln end function stepBound(Soln, step) #calculate the maximum allowable step in the proposed direction in (0 1] d = [step.z; step.s] #the proposed z and s directions t = [Soln.z; Soln.s] am = 1.0 id = findall(d .< 0) #leave d>=0 alone if length(id) > 0 a = t[id] ./ d[id] am = min(1.0, -maximum(a)) end return am end
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
10161
#The general quadratic programming formulation recognized by LightenQP """ mpcQP(V, q, A, b, C, g, d, u, h; settings) :OOQP + 'd≤x≤u' + 'h≤Cx' mpcQP(V, q, A, b, C, g, d, u; settings) :OOQP + 'd≤x≤u' mpcQP(V, q, C, g, d, u, h; settings) :OOQP + 'd≤x≤u' + 'h≤Cx' - 'Ax=b' mpcQP(V, q, A, b, C, g; settings) :OOQP mpcQP(V, q, d, u; settings) :OOQP + 'd≤x≤u' - 'Ax=b, Cx≤g' mpcQP(O::OOQP; settings) :OOQP wrapping `solveOOQP` for quadratic programming problems: `mpcQP(V, q, A, b, C, g, d, u, h)` for (OOQP + 'd≤x≤u' + 'h≤Cx') ```math min (1/2)x′Vx+x′q s.t. Ax=b∈R^{M} h≤Cx≤g∈R^{L} d≤x≤u∈R^{N} ``` `mpcQP(V, q, A, b, C, g, d, u)` for equality and inequality constraints, and lower and upper bounds (OOQP + 'd≤x≤u') ```math min (1/2)x′Vx+x′q s.t. Ax=b∈R^{M} Cx≤g∈R^{L} d≤x≤u∈R^{N} ``` `mpcQP(V, q, C, g, d, u, h)` for only inequality constraints, and lower and upper bounds (OOQP + 'd≤x≤u' + 'h≤Cx' - 'Ax=b') ```math min (1/2)x′Vx+x′q s.t. h≤Cx≤g∈R^{L} d≤x≤u∈R^{N} ``` `mpcQP(V, q, d, u)` for only lower and upper bounds (OOQP + 'd≤x≤u' - 'Ax=b, Cx≤g') ```math min (1/2)x′Vx+x′q s.t. d≤x≤u∈R^{N} ``` See [`Documentation for LightenQP.jl`](https://github.com/PharosAbad/LightenQP.jl/wiki) See also [`OOQP`](@ref), [`solveOOQP`](@ref), [`Solution`](@ref), [`Settings`](@ref) """ function mpcQP(V::Matrix{T}, q::Vector{T}, A::Matrix{T}, b::Vector{T}, C::Matrix{T}, g::Vector{T}, d::Vector{T}, u::Vector{T}, h::Vector{T}; settings=Settings{T}()) where {T} id = findall(d .> -Inf) iu = findall(u .< Inf) ih = findall(h .> -Inf) ig = findall(g .< Inf) N = length(q) N == length(d) || throw(DimensionMismatch("incompatible dimension: d")) N == length(u) || throw(DimensionMismatch("incompatible dimension: u")) Cg = [C[ig, :]; -Matrix{T}(I, N, N)[id, :]; Matrix{T}(I, N, N)[iu, :]; -C[ih, :]] gg = [g[ig]; -d[id]; u[iu]; -h[ih]] O = OOQP(V, q; A=A, b=b, C=Cg, g=gg) return solveOOQP(O; settings=settings) end #OOQP + 'd≤x≤u' function mpcQP(V::Matrix{T}, q::Vector{T}, A::Matrix{T}, b::Vector{T}, C::Matrix{T}, g::Vector{T}, d::Vector{T}, u::Vector{T}; settings=Settings{T}()) where {T} id = findall(d .> -Inf) iu = findall(u .< Inf) ig = findall(g .< Inf) N = length(q) N == length(d) || throw(DimensionMismatch("incompatible dimension: d")) N == length(u) || throw(DimensionMismatch("incompatible dimension: u")) Cg = [C[ig, :]; -Matrix{T}(I, N, N)[id, :]; Matrix{T}(I, N, N)[iu, :]] gg = [g[ig]; -d[id]; u[iu]] O = OOQP(V, q; A=A, b=b, C=Cg, g=gg) return solveOOQP(O; settings=settings) end #OOQP + 'd≤x≤u' + 'h≤Cx' - 'Ax=b' function mpcQP(V::Matrix{T}, q::Vector{T}, C::Matrix{T}, g::Vector{T}, d::Vector{T}, u::Vector{T}, h::Vector{T}; settings=Settings{T}()) where {T} id = findall(d .> -Inf) iu = findall(u .< Inf) ih = findall(h .> -Inf) ig = findall(g .< Inf) N = length(q) N == length(d) || throw(DimensionMismatch("incompatible dimension: d")) N == length(u) || throw(DimensionMismatch("incompatible dimension: u")) Cg = [C[ig, :]; -Matrix{T}(I, N, N)[id, :]; Matrix{T}(I, N, N)[iu, :]; -C[ih, :]] gg = [g[ig]; -d[id]; u[iu]; -h[ih]] O = OOQP(V, q; A=zeros(T, 0, N), b=zeros(T, 0), C=Cg, g=gg) return solveOOQP(O; settings=settings) end #OOQP function mpcQP(V::Matrix{T}, q::Vector{T}, A::Matrix{T}, b::Vector{T}, C::Matrix{T}, g::Vector{T}; settings=Settings{T}()) where {T} #alias for solveOOQP(V, q, A, b, C, g; settings=settings) O = OOQP(V, q; A=A, b=b, C=C, g=g) return solveOOQP(O; settings=settings) end function mpcQP(O::OOQP{T}; settings=Settings{T}()) where {T} #alias for solveOOQP(O; settings=settings) return solveOOQP(O; settings=settings) end #OOQP + 'd≤x≤u' - 'Ax=b, Cx≤g' function mpcQP(V::Matrix{T}, q::Vector{T}, d::Vector{T}, u::Vector{T}; settings=Settings{T}()) where {T} id = findall(d .> -Inf) iu = findall(u .< Inf) N = length(q) N == length(d) || throw(DimensionMismatch("incompatible dimension: d")) N == length(u) || throw(DimensionMismatch("incompatible dimension: u")) C = [-Matrix{T}(I, N, N)[id, :]; Matrix{T}(I, N, N)[iu, :]] g = [-d[id]; u[iu]] O = OOQP(V, q; A=zeros(T, 0, N), b=zeros(T, 0), C=C, g=g) return solveOOQP(O; settings=settings) end """ mpcLP(q, A, b, C, g, d, u; settings, min=true) mpcLP(q, A, b, C, g; settings, min=true) mpcLP(O::OOQP; settings, min=true) `mpcLP(O::OOQP; settings)`: wrapping `solveOOQP` for linear programming problems (set `V=0` in `OOQP`). If `min=false`, we maximize the objective function `mpcLP(q, A, b, C, g, d, u)` for equality and inequality constraints, and lower and upper bounds ```math min x′q s.t. Ax=b∈R^{M} Cx≤g∈R^{L} d≤x≤u∈R^{N} ``` `mpcLP(q, A, b, C, g)` for equality and inequality constraints ```math min x′q s.t. Ax=b∈R^{M} Cx≤g∈R^{L} ``` See [`Documentation for LightenQP.jl`](https://github.com/PharosAbad/LightenQP.jl/wiki) See also [`OOQP`](@ref), [`solveOOQP`](@ref), [`Solution`](@ref), [`Settings`](@ref) """ function mpcLP(q::Vector{T}, A::Matrix{T}, b::Vector{T}, C::Matrix{T}, g::Vector{T}; settings=Settings{T}(), min=true) where {T} N = length(q) sgn = min == true ? 1 : -1 O = OOQP(zeros(T, N, N), sgn * q; A=A, b=b, C=C, g=g) return solveOOQP(O; settings=settings) end function mpcLP(O::OOQP{T}; settings=Settings{T}(), min=true) where {T} (; A, C, q, b, g, N) = O sgn = min == true ? 1 : -1 O0 = OOQP(zeros(T, N, N), sgn * q; A=A, b=b, C=C, g=g) return solveOOQP(O0; settings=settings) end #OOQP + 'd≤x≤u' function mpcLP(q::Vector{T}, A::Matrix{T}, b::Vector{T}, C::Matrix{T}, g::Vector{T}, d::Vector{T}, u::Vector{T}; settings=Settings{T}(), min=true) where {T} id = findall(d .> -Inf) iu = findall(u .< Inf) ig = findall(g .< Inf) N = length(q) N == length(d) || throw(DimensionMismatch("incompatible dimension: d")) N == length(u) || throw(DimensionMismatch("incompatible dimension: u")) Cg = [C[ig, :]; -Matrix{T}(I, N, N)[id, :]; Matrix{T}(I, N, N)[iu, :]] gg = [g[ig]; -d[id]; u[iu]] sgn = min == true ? 1 : -1 O = OOQP(zeros(T, N, N), sgn * q; A=A, b=b, C=Cg, g=gg) return solveOOQP(O; settings=settings) end """ x, status = fPortfolio(O::OOQP, L::T=0.0; settings) x, status = fPortfolio(mu, O::OOQP; settings, check=true) find the minimum variance portfolio: See [`Portfolio Selection · LightenQP`](https://github.com/PharosAbad/LightenQP.jl/wiki/User-Guides#portfolio-selection-1) L=-Inf :FP(L=-Inf), LMFP (Lowest Mean Frontier Portfolio) L=+Inf :FP(L=+Inf), HMFP (Highest Mean Frontier Portfolio) HVEP (Highest Variance Efficient Portfolio) L=L0 :FP(L=L0), the frontier (minimum variance) portfolio at L=L0. L=0, LVEP (Lowest Variance Efficient Portfolio, also called GMVP, Global Minimum Variance Portfolio) mu=-Inf :FP(L=-Inf), LMFP (Lowest Mean Frontier Portfolio) mu=+Inf :FP(L=+Inf), HMFP (Highest Mean Frontier Portfolio) == HVEP (Highest Variance Efficient Portfolio) mu=mu0 :FP(mu=mu0), the frontier (minimum variance) portfolio at mu=mu0 if `check=false`, we do not check if mu is feasible or not (between lowest and highest mean) See also [`OOQP`](@ref), [`solveOOQP`](@ref), [`Solution`](@ref), [`Settings`](@ref) """ function fPortfolio(mu::T, O::OOQP{T}; settings=Settings{T}(), check=true) where {T} #FP(mu=mu) (; V, A, C, q, b, g, N, M, L) = O #tol = settings.tol mu1 = mu if check #make sure mu is feasible, otherwise, change mu to be the highest or lowest #HMFP (Highest Mean Frontier Portfolio) xH, status = mpcLP(q, A, b, C, g; settings=settings, min=false) #find the Highest mu if status == 0 error("mu for Highest Mean Frontier Portfolio: infeasible") elseif status < 0 error("mu for Highest Mean Frontier Portfolio: not converged") end muH = xH.x' * q if mu1 - muH > 0 #tol mu1 = muH if isfinite(mu) @warn "mu is higher than the highest muH, compute at muH" mu muH end else #LMFP (Lowest Mean Frontier Portfolio) xL, status = mpcLP(q, A, b, C, g; settings=settings) #find the Lowest mu if status == 0 error("mu for Lowest Mean Frontier Portfolio: infeasible") elseif status < 0 error("mu for Lowest Mean Frontier Portfolio: not converged") end muL = xL.x' * q if muL - mu1 > 0 #tol mu1 = muL if isfinite(mu) @warn "mu is lower than the lowest muL, compute at muL" mu muL end end end end #@ given mu1 qq = zeros(T, N) Aq = [A; q'] bq = [b; mu1] M += 1 Q = OOQP{T}(V, Aq, C, qq, bq, g, N, M, L) return solveOOQP(Q; settings=settings) end function fPortfolio(O::OOQP{T}, L::T=0.0; settings=Settings{T}()) where {T} #FP(L=L) (; V, A, C, q, b, g, N, M) = O if isfinite(L) #@ given L if L == 0.0 qq = zeros(T, N) else qq = -L * q end Q = OOQP{T}(V, A, C, qq, b, g, N, M, O.L) return solveOOQP(Q; settings=settings) end #L == ±Inf, using LP to find HMEP LMEP min = L == Inf ? false : true x, status = mpcLP(q, A, b, C, g; settings=settings, min=min) if status == 0 error("mu for Highest/Lowest Mean Frontier Portfolio: infeasible") elseif status < 0 error("mu for Highest/Lowest Mean Frontier Portfolio: not converged") end mu = x.x' * q qq = zeros(T, N) Aq = [A; q'] bq = [b; mu] M += 1 Q = OOQP{T}(V, Aq, C, qq, bq, g, N, M, O.L) return solveOOQP(Q; settings=settings) end
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
5665
# Problem-Algorithm-Solver pattern """ OOQP(V, A, C, q::Vector{T}, b, g) where T OOQP(V, q::Vector{T}; A=A, b=b, C=C, g=g) where T define the following convex quadratic programming problems (called OOQP) ```math min (1/2)x′Vx+q′x s.t. Ax=b ∈ R^{M} Cx≤g ∈ R^{L} ``` default values for OOQP(V, q; kwargs...): A = ones(1,N), b = [1], C = -I, g = zeros(N). Which define a portfolio optimization without short-sale For portfolio optimization OOQP(V, q) : for no short-sale OOQP(V, q, u) : for bounds 0 <= x <= u, and thus A = ones(1,N), b = [1], C = [-I; I], g = [zeros(N); u] See [`Documentation for LightenQP.jl`](https://github.com/PharosAbad/LightenQP.jl/wiki) See also [`solveOOQP`](@ref), [`Solution`](@ref), [`mpcQP`](@ref), [`Settings`](@ref) """ struct OOQP{T<:AbstractFloat} V::Matrix{T} A::Matrix{T} C::Matrix{T} q::Vector{T} b::Vector{T} g::Vector{T} N::Int M::Int L::Int end OOQP(args...) = OOQP{Float64}(args...) function OOQP(V, q::Vector{T}; N = length(q), A=ones(1, N), b=ones(1), C=-Matrix(I, N, N), g=zeros(N)) where {T} #T = typeof(q).parameters[1] #N = length(q) (N, N) == size(V) || throw(DimensionMismatch("incompatible dimension: V")) qq = copy(vec(q)) #make sure vector and a new copy Vs = convert(Matrix{T}, (V + V') / 2) #make sure symmetric #remove Inf bounds g = vec(g) ik = findall(.!isinf.(g)) gb = g[ik] Cb = C[ik, :] M = length(b) L = length(gb) (M, N) == size(A) || throw(DimensionMismatch("incompatible dimension: A")) (L, N) == size(Cb) || throw(DimensionMismatch("incompatible dimension: C")) OOQP{T}(Vs, convert(Matrix{T}, copy(A)), #make a copy, just in case it is modified somewhere convert(Matrix{T}, Cb), qq, convert(Vector{T}, copy(vec(b))), convert(Vector{T}, gb), N, M, L) end function OOQP(V, q::Vector{T}, u) where {T} #T = typeof(q).parameters[1] N = length(q) (N, N) == size(V) || throw(DimensionMismatch("incompatible dimension: V")) A = ones(T, 1, N) b = ones(T, 1) iu = findall(u .< Inf) C = [-Matrix{T}(I, N, N); Matrix{T}(I, N, N)[iu, :]] g = [zeros(T, N); u[iu]] OOQP(V, q; A=A, b=b, C=C, g=g) end function OOQP(V, A, C, q, b, g) OOQP(V, q; A=A, b=b, C=C, g=g) end #OOQP + bounds d <= x <= u function OOQP(V, A, C, q::Vector{T}, b, g, d, u) where {T} #T = typeof(q).parameters[1] N = length(q) (N, N) == size(V) || throw(DimensionMismatch("incompatible dimension: V")) id = findall(d .> -Inf) iu = findall(u .< Inf) ig = findall(g .< Inf) Ce = [C[ig, :]; -Matrix{T}(I, N, N)[id, :]; Matrix{T}(I, N, N)[iu, :]] ge = [g[ig]; -d[id]; u[iu]] OOQP(V, q; A=A, b=b, C=Ce, g=ge) end """ Settings(Q::OOQP; kwargs...) The default Settings to given OOQP Settings(; kwargs...) The default Settings is set by Float64 type Settings{T<:AbstractFloat}(; kwargs...) kwargs are from the fields of Settings{T<:AbstractFloat} for Float64 and BigFloat maxIter::Int64 #777 scaleStep::T #0.99 a crude step scaling factor (using Mehrotra's heuristic maybe better) tol::T #2^-26 ≈ 1.5e-8 general (not use in OOQP solver) tolMu::T #2^-52 ≈ 2.2e-16 violation of the complementarity condition tolR::T #2^-49 ≈ 1.8e-15 norm(resid) <= tolR * norm(OOQP) minPhi::T #2^23 = 8388608 ≈ 1e7 phi_min_history, not a foolproof test see [`ooqp-userguide.pdf`](http://www.cs.wisc.edu/~swright/ooqp/ooqp-userguide.pdf) or [`Working with the QP Solver`](https://github.com/emgertz/OOQP/blob/master/doc-src/ooqp-userguide/ooqp4qpsolver.tex) """ struct Settings{T<:AbstractFloat} maxIter::Int64 #777 scaleStep::T # 0.99 tol::T #2^-26 tolMu::T #2^-47 tolR::T #2^-37 minPhi::T #2^23 end Settings(; kwargs...) = Settings{Float64}(; kwargs...) function Settings{Float64}(; maxIter=777, scaleStep=0.99, tol=2^-26, tolMu=2^-52, tolR=2^-49, minPhi=2^23) Settings{Float64}(maxIter, scaleStep, tol, tolMu, tolR, minPhi) end function Settings{BigFloat}(; maxIter=777, scaleStep=0.99, tol=2^-76, tolMu=2^-87, tolR=2^-77, minPhi=2^23) Settings{BigFloat}(maxIter, scaleStep, tol, tolMu, tolR, minPhi) end function Settings(Q::OOQP{T}; kwargs...) where {T} Settings{T}(; kwargs...) end """ struct Solution Solution strcture to the following convex quadratic programming problems (called OOQP) ```math min (1/2)x′Vx+q′x s.t. Ax=b ∈ R^{M} Cx≤g ∈ R^{L} ``` x : primal solution y : equality multipliers, dual variables z : inequality multipliers, dual variables s : slack variables See [`Documentation for LightenQP.jl`](https://github.com/PharosAbad/LightenQP.jl/wiki) See also [`OOQP`](@ref), [`solveOOQP`](@ref), [`mpcQP`](@ref) """ struct Solution{T<:AbstractFloat} x::Vector{T} y::Vector{T} z::Vector{T} s::Vector{T} end function Solution(Q::OOQP{T}) where {T} (; N, M, L) = Q x = zeros(T, N) y = zeros(T, M) z = ones(T, L) s = ones(T, L) Solution(x, y, z, s) end struct Residuals{T<:AbstractFloat} rV::Vector{T} rA::Vector{T} rC::Vector{T} rS::Vector{T} end function Residuals(Q::OOQP{T}) where {T} (; N, M, L) = Q rV = zeros(T, N) rA = zeros(T, M) rC = zeros(T, L) rS = zeros(T, L) Residuals(rV, rA, rC, rS) end
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
code
249
using LightenQP using Test @testset "LightenQP.jl" begin V = [1/100 1/80 1/100 1/80 1/16 1/40 1/100 1/40 1/25] E = [109 / 100; 23 / 20; 119 / 100] Q = OOQP(V, -E) x, status = mpcQP(Q) @test status > 0 @test isapprox(x.x[3], 1) end
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "MIT" ]
1.0.9
b2b81760deb369c3b6056f6a09694f1fde369c43
docs
2362
___LightenQP.jl___ [![Build Status](https://github.com/PharosAbad/LightenQP.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/PharosAbad/LightenQP.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://github.com/PharosAbad/LightenQP.jl/wiki) <h1 align="center" margin=0px> A pure Julia implementation of OOQP </h1> <p align="center"> <a href="#features">Features</a> • <a href="#installation">Installation</a> • <a href="#license-">License</a> • <a href="https://github.com/PharosAbad/LightenQP.jl/wiki">Documentation</a> </p> **LightenQP.jl** solves the following convex quadratic programming problems (called `OOQP`): $$ \begin{array} [c]{cl} \min & \frac{1}{2}\mathbf{x}^{\prime}\mathbf{Vx}+\mathbf{x}^{\prime}% \mathbf{q}\\ s.t. & \mathbf{Ax}=\mathbf{b}\in\mathbb{R}^{M}\\ & \mathbf{Cx}\leq\mathbf{g}\in\mathbb{R}^{L} \end{array} $$ with positive semi-definite symmetric matrix $\mathbf{V}\in\mathbb{R}^{N\times N}$. The general quadratic programming formulation solved by `LightenQP` is (`OOQP + d≤x≤u + h≤Cx`) $$ \begin{array} [c]{cl} \min & \frac{1}{2}\mathbf{x}^{\prime}\mathbf{Vx}+\mathbf{x}^{\prime} \mathbf{q}\\ s.t. & \mathbf{Ax}=\mathbf{b}\in\mathbb{R}^{M}\\ & \mathbf{h}\leq\mathbf{Cx}\leq\mathbf{g}\in\mathbb{R}^{L}\\ & \boldsymbol{d}\leq\mathbf{x}\leq\boldsymbol{u}\in\mathbb{R}^{N} \end{array} $$ ## Features * __Light Weight__: 100+ lines Julia code. Which follows closely the the implementation of the C/C++ solver [OOQP](https://github.com/emgertz/OOQP) * __Fast__: [Speed and Accuracy](https://github.com/PharosAbad/LightenQP.jl/wiki/Speed-and-Accuracy) * __Versatile__: solving a general quadratic programming problem mentioned above. $\mathbf{V}$ can be positive definite or positive semi-definite * __Open Source__: Our code is available on [GitHub](https://github.com/PharosAbad/LightenQP.jl) and distributed under the MIT License * __Arbitrary Precision Arithmetic__: fully support for `BigFloat` ## Installation __LightenQP.jl__ can be added by - `import Pkg; Pkg.add("LightenQP")` - `pkg> add LightenQP` - `pkg> dev LightenQP` for testing nightly version. To use the registered version again `pkg> free LightenQP` ## License 🔍 This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
LightenQP
https://github.com/PharosAbad/LightenQP.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1199
using Documenter, MultiscaleGraphSignalTransforms makedocs( sitename="MultiscaleGraphSignalTransforms.jl", format = Documenter.HTML(collapselevel = 1), authors = "Jeff Irion, Haotian Li, Naoki Saito, Yiqun Shao", clean = true, pages = [ "Home" => "index.md", "Examples" => [ "1D Path" => "examples/P64.md", "2D Lattice" => "examples/Grid7x3.md", "Sunflower Graph" => "examples/Sunflower.md", ], "Functions" => [ "Recursive Graph Partitioning" => "functions/Partition.md", "Hierarchical Graph Laplacian Eigen Transform" => "functions/HGLET.md", "Generalized Haar-Walsh Transform" => "functions/GHWT.md", "extended Generalized Haar-Walsh Transform" => "functions/eGHWT.md", "Natural Graph Wavelet Dictionaries" => "functions/NGWD.md", "Utils" => "functions/Utils.md", ], ] ) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information. deploydocs( repo = "github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git" )
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1323
module BasisSpecification using ..GraphSignal, ..GraphPartition, LinearAlgebra export BasisSpec #, bsfull, bs_haar, bs_level # BasisSpec data structure and constructors """ BS = BasisSpec(dvec, dvec_loc, c2f, description) is a data structure for a BasisSpec object contaning the following fields: * `levlist::Vector{Tuple{Int, Int}}`: the integer sequence that specifies a particular basis * `c2f::Bool`: if true (default), this indicates that the basis comes from the coarse-to-fine dictionary; if false, this indicates that the basis comes from the fine-to-coarse dictionary * `description::String`: a description of the specified basis Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) | Translated to julia and revised by Naoki Saito, Feb. 22, 2017 Modified by Yiqun Shao, May. 20, 2018 """ mutable struct BasisSpec levlist::Vector{Tuple{Int, Int}} c2f::Bool description::String # An inner constructor here. function BasisSpec(levlist::Vector{Tuple{Int, Int}}; c2f::Bool = true, description::String = "") new(levlist, c2f, description ) end # of BasisSpec constructor end # of type BasisSpec end # of module BasisSpecification
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
39261
module GHWT include("utils.jl") using ..GraphSignal, ..GraphPartition, ..BasisSpecification, LinearAlgebra include("common.jl") export ghwt_core!, ghwt_analysis!, fine2coarse!, ghwt_synthesis, ghwt_c2f_bestbasis, ghwt_f2c_bestbasis, ghwt_bestbasis, GHWT_jkl """ ghwt_core!(GP::GraphPart) performs the forward GHWT transform, which computes tag and compinfo of GP, but not the expansion coefficients. ### Input Arguments * `GP::GraphPart`: a GraphPart object (with or without tag and compinfo data); note that tag and compinfo will be modified after this function is executed """ function ghwt_core!(GP::GraphPart) # # 0. Preliminaries # rs = GP.rs # for simple notation! (N, jmax) = Base.size(rs) N = N - 1 # tag -- when expressed in binary, tag indicates the sequence of # average (0's) and difference (1's) operations used to obtain the given # basis vector if isempty(GP.tag) GP.tag = zeros(Int, N, jmax) end tag = GP.tag # for simple notation! # allocate space for compinfo (used for synthesis from f2c dictionary) # if tag == 0 && n == 1: compinfo = 0 # if tag == 0 && n >= 2: compinfo = n1 # if tag == 1: compinfo = n2 # if tag >= 2 && coeff is formed from 2 coeffs: compinfo = 1 # if tag >= 2 && coeff is formed from 1 coeff: compinfo = 0 if isempty(GP.compinfo) GP.compinfo = zeros(Int, N, jmax) end compinfo = GP.compinfo # for simple notation! # # 1. Perform the transform # for j = (jmax - 1):-1:1 # # Bottom-1 (jmax-1) to up to the coarsest (j=1) regioncount = count(!iszero,rs[:, j]) - 1 for r = 1:regioncount rs1 = rs[r, j] # the start of the 1st subregion rs3 = rs[r + 1, j] # 1 + the end of the 2nd subregion n = rs3 - rs1 # # of points in the current region if n > 1 # single node region passes this part rs2 = rs1 + 1 # the start of the 2nd subregion while rs2 < rs3 && tag[rs2, j + 1] != 0 ### && rs2 < N+1 rs2 += 1 end if rs2 == rs3 # the parent region is a copy of the subregion tag[rs1:(rs3 - 1), j] = tag[rs1:(rs3 - 1), j + 1] else # the parent region has 2 child regions n1 = rs2 - rs1 # # of pts in the 1st subregion n2 = rs3 - rs2 # # of pts in the 2nd subregion # SCALING COEFFICIENT (n > 1) compinfo[rs1, j] = n1; # HAAR COEFFICIENT compinfo[rs1 + 1, j] = n2; tag[rs1 + 1, j] = 1 # WALSH COEFFICIENTS # sweep through the coefficients in subregions 1 & 2 parent = rs1 + 2 # ind of the new coeffs to be created on level j child1 = rs1 + 1 # ind of the current coeffs in subregion 1 child2 = rs2 + 1 # ind of the current coeffs in subregion 2 while parent < rs3 # no matching coefficient (use subregion 1) if child1 < rs2 && (child2 == rs3 || tag[child1, j + 1] < tag[child2, j + 1]) tag[parent, j] = 2 * tag[child1, j + 1] child1 += 1; parent += 1 # no matching coefficient (use subregion 2) elseif child2 < rs3 && (child1 == rs2 || tag[child2, j + 1] < tag[child1, j + 1]) tag[parent, j] = 2 * tag[child2, j + 1] child2 += 1; parent += 1 # matching coefficients else tag[parent, j] = 2 * tag[child1, j + 1] #tag[parent + 1, j] = 2 * tag[child1, j + 1] + 1 tag[parent + 1, j] = tag[parent, j] + 1 compinfo[parent, j] = 1; compinfo[parent + 1, j] = 1 child1 += 1; child2 += 1; parent += 2 end # of if child1 < rs2 ... end # of while end # of if rs2 == rs3 ... elseif n <= 0 # n must be positive error("n must be positive: n = ", n) end # of if n > 1 ... elseif n <= 0 ...; note: do nothing for n==1 end # of for r = 1:regioncount end # of for j = (jmax - 1):-1:1 end # of function ghwt_core! """ ghwt_core!(GP::GraphPart, dmatrix::Array{Float64,3}) performs the forward GHWT transform, which generates expansion coefficients, tag, and compinfo. ### Input Arguments * `GP::GraphPart`: a GraphPart object (with or without tag and compinfo data); note that tag and compinfo will be modified after this function is executed * `dmatrix::Array{Float64,3}`: a matrix of expansion coefficients with only the last column filled in as the original input signal(s) `f`; after this function is executed, this matrix contains whole expansion coefficients of the input signal(s) relative to the GHWT dictionary """ function ghwt_core!(GP::GraphPart, dmatrix::Array{Float64,3}) # # 0. Preliminaries # rs = GP.rs # for simple notation! (N, jmax) = Base.size(rs) N = N - 1 # tag -- when expressed in binary, tag indicates the sequence of # average (0's) and difference (1's) operations used to obtain the given # basis vector if isempty(GP.tag) GP.tag = zeros(Int, N, jmax) end tag = GP.tag # for simple notation! # allocate space for compinfo (used for synthesis from fine-to-coarse dictionary) # if tag == 0 && n == 1: compinfo = 0 # if tag == 0 && n >= 2: compinfo = n1 # if tag == 1: compinfo = n2 # if tag >= 2 && coeff is formed from 2 coeffs: compinfo = 1 # if tag >= 2 && coeff is formed from 1 coeff: compinfo = 0 if isempty(GP.compinfo) GP.compinfo = zeros(Int, N, jmax) end compinfo = GP.compinfo # for simple notation! # # 1. Perform the transform # for j = (jmax - 1):-1:1 # Bottom-1 (jmax-1) to up to the coarsest (j=1) regioncount = count(!iszero,rs[:, j]) - 1 for r = 1:regioncount rs1 = rs[r, j] # the start of the 1st subregion rs3 = rs[r + 1, j] # 1 + the end of the 2nd subregion n = rs3 - rs1 # # of points in the current region if n == 1 # single node region # SCALING COEFFICIENT (n == 1) dmatrix[rs1, j, :] = dmatrix[rs1, j + 1, :] elseif n > 1 rs2 = rs1 + 1 # the start of the 2nd subregion while rs2 < rs3 && tag[rs2, j + 1] != 0 ### && rs2 < N+1 rs2 += 1 end if rs2 == rs3 # the parent region is a copy of the subregion dmatrix[rs1:(rs3 - 1), j, :] = dmatrix[rs1:(rs3 - 1), j + 1, :] tag[rs1:(rs3 - 1), j] = tag[rs1:(rs3 - 1), j + 1] else # the parent region has 2 child regions n1 = rs2 - rs1 # # of pts in the 1st subregion n2 = rs3 - rs2 # # of pts in the 2nd subregion # SCALING COEFFICIENT (n > 1) dmatrix[rs1, j, :] = ( sqrt(n1) * dmatrix[rs1, j + 1, :] + sqrt(n2) * dmatrix[rs2, j + 1, :] ) / sqrt(n) compinfo[rs1, j] = n1 # HAAR COEFFICIENT dmatrix[rs1 + 1, j, :] = ( sqrt(n2) * dmatrix[rs1, j + 1, :] - sqrt(n1) * dmatrix[rs2, j + 1, :] ) / sqrt(n) # Note these sqrt's arguments are not typos!! compinfo[rs1 + 1, j] = n2; tag[rs1 + 1, j] = 1 # WALSH COEFFICIENTS # sweep through the coefficients in subregions 1 & 2 parent = rs1 + 2 # ind of the new coeffs to be created on level j child1 = rs1 + 1 # ind of the current coeffs in subregion 1 child2 = rs2 + 1 # ind of the current coeffs in subregion 2 while parent < rs3 # no matching coefficient (use subregion 1) if child1 < rs2 && (child2 == rs3 || tag[child1, j + 1] < tag[child2, j + 1]) dmatrix[parent, j, :] = dmatrix[child1, j + 1, :] tag[parent, j] = 2 * tag[child1, j + 1] child1 += 1; parent += 1 # no matching coefficient (use subregion 2) elseif child2 < rs3 && (child1 == rs2 || tag[child2, j + 1] < tag[child1, j + 1]) dmatrix[parent, j, :] = dmatrix[child2, j + 1, :] tag[parent, j] = 2 * tag[child2, j + 1] child2 += 1; parent += 1 # matching coefficients else dmatrix[parent, j, :] = ( dmatrix[child1, j + 1, :] + dmatrix[child2, j + 1, :] ) / sqrt(2) tag[parent, j] = 2 * tag[child1, j + 1] compinfo[parent, j] = 1 dmatrix[parent + 1, j, :] = ( dmatrix[child1, j + 1, :] - dmatrix[child2, j + 1, :] ) / sqrt(2) #tag[parent + 1, j] = 2 * tag[child1, j + 1] + 1 tag[parent + 1, j] = tag[parent, j] + 1 compinfo[parent + 1, j] = 1 child1 += 1; child2 += 1; parent += 2 end # of if child1 < rs2 ... end # of while end # of if rs2 == rs3 ... else # n must be positive error("n must be positive: n = ", n) end # of if n == 1 ... elseif n > 1 ... end # of for r = 1:regioncount end # of for j = (jmax - 1):-1:1 end # of function ghwt_core! """ dmatrix = ghwt_analysis!(G::GraphSig, GP::GraphPart = nothing, c2f::Bool = true) For a GraphSig object `G`, generate the matrix of GHWT expansion coefficients ### Input Arguments * `G::GraphSig`: an input GraphSig object * `GP::GraphPart`: an input GraphPart object (optional); after this function is run, `GP`'s `compinfo`, `tag`, etc. are filled ### Output Argument * `dmatrix::Array{Float64,3}`: the 3D array of expansion coefficients (i.e., for each input signal vector, the matrix of coefficients; hence, for multiple input signals, the coefficients are organized as a 3D array) """ function ghwt_analysis!(G::GraphSig; GP::GraphPart = nothing, c2f::Bool = true) # # 0. Preliminaries # if isnothing(GP) GP = partition_tree_fiedler(G) end # Simplify the subsequent notation without overhead. We can do this # since `ind`, `rs`, `f` share the same memory as `GP.ind`, `GP.rs`, `G.f` ind = GP.ind rs = GP.rs f = G.f (N, jmax) = Base.size(rs) N = N - 1 # allocate space for the expansion coefficients fcols = size(f, 2) dmatrix = zeros(N, jmax, fcols) dmatrix[:, jmax, :] = f[ind, :] ## 1. Perform the transform # generate expansion coefficients, tag, and compinfo ghwt_core!(GP, dmatrix) # fill in the remaining (i.e. fine-to-coarse) GraphPart fields if c2f return dmatrix else return fine2coarse!(GP, dmatrix=dmatrix, coefp = true) end end # of ghwt_analysis! """ (dmatrixf2c, IX) = fine2coarse!(GP::GraphPart; dmatrix::Array{Float64,3} = zeros(0, 0, 0), coefp::Bool = false, indp::Bool = false) Fill in the fine-to-coarse info (rs2f2c, tagf2c, and compinfof2c) in a GraphPart object. Also, rearrange a matrix of expansion coefficients. ### Input Arguments * `GP::GraphPart`: an input GraphPart object without fine-to-coarse info (rsf2c, tagf2c, compinfof2c); after this function, rsf2c, tagf2c, compinfof2c are filled. Note that rs, tag, compinfo are intact. * `dmatrix::Array{Float64,3}`: a matrix of expansion coefficients in coarse-to-fine arrangement (default: null matrix) * `coefp::Bool`: a flag to return the rearranged f2c coefficients (default: false) * `indp::Bool`: a flag to return the reordering index (default: false) ### Output Arguments * `dmatrixf2c::Array{Float64,3}`: a matrix of expansion coefficients in fine-to-coarse arrangement (if requested) * `IX::Vector{Unsigned}`: the reordering index for all levels """ function fine2coarse!(GP::GraphPart; dmatrix::Array{Float64,3} = zeros(0, 0, 0), coefp::Bool = false, indp::Bool = false) # # 0. Preliminaries # # get constants (N, jmax) = Base.size(GP.rs) N = N - 1 # allocate spaces if isempty(GP.rsf2c) GP.rsf2c = zeros(Int, N + 1, jmax) end GP.rsf2c[1, :] .= 1 GP.rsf2c[2, 1] = N + 1 if isempty(GP.tagf2c) GP.tagf2c = zeros(Int, N, jmax) end if isempty(GP.compinfof2c) GP.compinfof2c = zeros(Int, N, jmax) end IX = zeros(Int, N, jmax) if coefp dmatrixf2c = zeros(Base.size(dmatrix)) end # make sure the coarse-to-fine tag field is filled in if isempty(GP.tag) || isempty(GP.compinfo) ghwt_core!(GP) end # for simple notation! ind = GP.ind; rs = GP. rs tag = GP.tag; compinfo = GP.compinfo rsf2c = GP.rsf2c; tagf2c = GP.tagf2c; compinfof2c = GP.compinfof2c # # 1. Generate the fine-to-coarse dictionary # # put the coefficients into fine-to-coarse order for j = 1:jmax # put the basis into tag order # MATLAB: [GP.tagf2c(:,j),IX(:,j)] = sort(GP.tag(:,jmax+1-j)); IX[:, j] = sortperm(tag[:, jmax + 1 - j]) tagf2c[:, j] = tag[IX[:, j], jmax + 1 - j] compinfof2c[:, j] = compinfo[IX[:, j], jmax + 1 - j] if coefp dmatrixf2c[:, j, :] = dmatrix[IX[:, j], jmax + 1 - j, :] end # fill in the fine-to-coarse regionstarts if j > 1 rsf2crow = 2 for row = 2:N if tagf2c[row, j] > tagf2c[row - 1, j] rsf2c[rsf2crow, j] = row rsf2crow += 1 end end rsf2c[rsf2crow, j] = N + 1 end end # of for j = 1:jmax # # 2. Return the appropriate variables if requested # if coefp && indp return dmatrixf2c, IX elseif coefp && !indp return dmatrixf2c elseif !coefp && indp return IX end end # of function fine2coarse! """ f = ghwt_synthesis(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec) Given a vector of GHWT expansion coefficients and info about the graph partitioning and the choice of basis, reconstruct the signal ### Input Arguments * `dvec::Matrix{Float64}`: the expansion coefficients corresponding to the chosen basis * `GP::GraphPart`: an input GraphPart object * `BS::BasisSpec`: an input BasisSpec object ### Output Arguments * `f::Matrix{Float64}`: the reconstructed signal(s) """ function ghwt_synthesis(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec) # # 0. Preliminaries # # if necessary, fill in the tag info in GP if isempty(GP.tag) ghwt_core!(GP) end # figure out which dictionary is used: coarse-to-fine or fine-to-coarse if !BS.c2f && isempty(GP.tagf2c) fine2coarse!(GP) end # constants N = Base.length(GP.ind) jmax = Base.size(GP.rs, 2) fcols = Base.size(dvec, 2) # fill in the appropriate entries of dmatrix dmatrix = dvec2dmatrix(dvec, GP, BS) # # 1. Synthesis from the basis dictionary # if BS.c2f # for coarse-to-fine case # for simpler notation! dvec_loc = zeros(Int, size(GP.tag)) for i = 1:length(BS.levlist) dvec_loc[BS.levlist[i][1], BS.levlist[i][2]] = 1 end rs = GP.rs tag = GP.tag for j = 1:(jmax - 1) # from top to bottom-1 regioncount = count(!iszero, rs[:, j]) - 1 for r = 1:regioncount rs1 = rs[r, j] # the start of the 1st subregion rs3 = rs[r + 1, j] # 1 + the end of the 2nd subregion n = rs3 - rs1 # # of points in the current region # only proceed forward if coefficients do not exist #if count(!iszero, dmatrix[rs1:(rs3 - 1), j + 1, :]) == 0 && # count(!iszero, dmatrix[rs1:(rs3 - 1), j, :]) > 0 if count(!iszero, dvec_loc[rs1:(rs3-1),j]) > 0 if n == 1 # single node region # SCALING COEFFICIENT (n == 1) if dvec_loc[rs1,j] == 1 dmatrix[rs1, j + 1, :] = dmatrix[rs1, j, :] dvec_loc[rs1,j+1] = 1 end elseif n > 1 rs2 = rs1 + 1 # the start of the 2nd subregion while rs2 < rs3 && tag[rs2, j + 1] != 0 ### && rs2 < N+1 rs2 += 1 end if rs2 == rs3 # the parent is a copy of the subregion if dvec_loc[rs1:rs3-1,j] == 1 dmatrix[rs1:(rs3 - 1), j + 1, :] = dmatrix[rs1:(rs3 - 1), j, :] dvec_loc[rs1:rs3-1,j+1] = 1 end else # the parent region has 2 child regions n1 = rs2 - rs1 # # of pts in the 1st subregion n2 = rs3 - rs2 # # of pts in the 2nd subregion # SCALING COEFFICIENTS (n > 1) if dvec_loc[rs1,j] == 1 && dvec_loc[rs1+1,j] == 1 dmatrix[rs1, j + 1, :] = ( sqrt(n1) * dmatrix[rs1, j, :] + sqrt(n2) * dmatrix[rs1 + 1, j, :] ) / sqrt(n) # HAAR COEFFICIENTS dmatrix[rs2, j + 1, :] = ( sqrt(n2) * dmatrix[rs1, j, :] - sqrt(n1) * dmatrix[rs1 + 1, j, :] ) / sqrt(n) dvec_loc[rs1,j+1] = 1 dvec_loc[rs2,j+1] = 1 end # WALSH COEFFICIENTS # search through the remaining coefs in each subregion parent = rs1 + 2 child1 = rs1 + 1 child2 = rs2 + 1 while child1 < rs2 || child2 < rs3 # subregion 1 has the smaller tag if child2 == rs3 || (tag[child1, j + 1] < tag[child2, j + 1] && child1 < rs2) if dvec_loc[parent,j]==1 dmatrix[child1, j + 1, :] = dmatrix[parent, j, :] dvec_loc[child1, j+1] =1 end child1 += 1; parent += 1 # subregion 2 has the smaller tag elseif child1 == rs2 || (tag[child2, j + 1] < tag[child1, j + 1] && child2 < rs3) if dvec_loc[parent, j] == 1 dmatrix[child2, j + 1, :] = dmatrix[parent, j, :] dvec_loc[child2, j+1] = 1 end child2 += 1; parent += 1 # both subregions have the same tag else if dvec_loc[parent,j] == 1 && dvec_loc[parent+1, j] == 1 dmatrix[child1, j + 1, :] = ( dmatrix[parent, j, :] + dmatrix[parent + 1, j, :] ) / sqrt(2) dmatrix[child2, j + 1, :] = ( dmatrix[parent, j, :] - dmatrix[parent + 1, j, :] ) / sqrt(2) dvec_loc[child1,j+1]=1 dvec_loc[child2,j+1]=1 end child1 += 1; child2 += 1; parent += 2 end # of if child2 == r3 ... end # of while child1 < rs2 ... end # of if rs2 == rs3 ... else end # of if n == 1 ... elseif n > 1 ... end # of if countnz(...) end # of for r = 1:regioncount end # of for j = 1:(jmax - 1) # MATLAB: if fcols == 1 # f = dmatrix[:, end] # else # f = reshape(dmatrix[:, end, :], N, fcols) # end # GS.f = dmatrix[:, end, :] # Do this later for clarity else # for fine-to-coarse case # for simpler notation! rsf2c = GP.rsf2c tagf2c = GP.tagf2c compinfof2c = GP.compinfof2c for j = (jmax - 1):-1:1 # from bottom-1 to top regioncount = count(!iszero, rsf2c[:, j]) - 1 for r = 1:regioncount rs1 = rsf2c[r, j] # the start of the 1st subregin rs3 = rsf2c[r + 1, j] # 1 + the end of the 2nd subregion # only proceed forward if coefficients do not exist if count(!iszero, dmatrix[rs1:(rs3 - 1), j, :]) == 0 && count(!iszero, dmatrix[rs1:(rs3 - 1), j + 1, :]) > 0 # one subregion ==> copy the coefficients if tagf2c[rs1, j + 1] == tagf2c[rs3 - 1, j + 1] dmatrix[rs1:(rs3 - 1), j, :] = dmatrix[rs1:(rs3 - 1), j + 1, :] # two subregions ==> compute the coefficients else rs2 = rs1 + 1 # the start of the 2nd subregion while rs2 < rs3 && tagf2c[rs1, j + 1] == tagf2c[rs2, j + 1] ### && rs2 < N+1 rs2 += 1 end if rs2 == rs3 # the parent is a copy of the subregion # no need to do the following # dmatrix[rs1:(rs3 - 1), (j + 1) , :] = # dmatrix[rs1:(rs3 - 1) , j, :] nothing else # the parent region has 2 child regions parent = rs1 # the current coef in the parent child1 = rs1 # the current coefs in the children child2 = rs2 # SCALING & HAAR COEFFICIENTS if tagf2c[rs1, j] == 0 while parent < rs3 # 1 coef formed from 1 coef if compinfof2c[child1, j + 1] == 0 dmatrix[parent, j, :] = dmatrix[child1, j + 1, :] parent += 1; child1 += 1 # 2 coefs formed from 2 coefs else n1 = compinfof2c[child1, j + 1] n2 = compinfof2c[child2, j + 1] n = n1 + n2 # # of points in the parent # SCALING COEFFICIENT dmatrix[parent, j, :] = ( sqrt(n1) * dmatrix[child1, j + 1, :] + sqrt(n2) * dmatrix[child2, j + 1, :] ) / sqrt(n) # HAAR COEFFICIENT dmatrix[parent + 1, j, :] = ( sqrt(n2) * dmatrix[child1, j + 1, :] - sqrt(n1) * dmatrix[child2, j + 1, :] ) / sqrt(n) parent += 2; child1 += 1; child2 += 1 end end # of while # WALSH COEFFICIENTS else while parent < rs3 # 1 coef formed from 1 coef if compinfof2c[child1, j + 1] == 0 dmatrix[parent, j, :] = dmatrix[child1, j + 1, :] parent += 1; child1 += 1 # 2 coefs formed from 2 coefs else dmatrix[parent, j, :] = ( dmatrix[child1, j + 1, :] + dmatrix[child2, j + 1, :] ) / sqrt(2) dmatrix[parent + 1, j, :] = ( dmatrix[child1, j + 1, :] - dmatrix[child2, j + 1, :] ) / sqrt(2) parent += 2; child1 += 1; child2 += 1 end # of if compinfof2c[...] end # of while parent < rs3 end # of if tagf2c[rs1, j] == 0 ... else ... end # of if rs2 == rs3 ... else ... end # of if tagf2c[rs1, j + 1] == tagf2c[rs3 - 1, j + 1] ... end # of if countnz(dmatrix[rs1:(rs3 - 1), j, :]) == 0 ... end # for r = 1:regioncount end # for j=(jmax - 1):-1:1 # GS.f = dmatrix[:, 1, :] end # of if BS.c2f ... else ... # # 2. Final prepartion for returning variables # ftemp = dmatrix[:, 1, :] # for fine-to-coarse and make f available if BS.c2f ftemp = dmatrix[:, end, :] # for coarse-to-fine end # put the reconstructed values in the correct order and return it. f = zeros(size(ftemp)) f[GP.ind, :] = ftemp return f end # of function ghwt_synthesis (without G input) """ (f, GS) = ghwt_synthesis(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec, G::GraphSig) Given a vector of GHWT expansion coefficients and info about the graph partitioning and the choice of basis, reconstruct the signal ### Input Arguments * `dvec::Matrix{Float64}`: the expansion coefficients corresponding to the chosen basis * `GP::GraphPart`: an input GraphPart object * `BS::BasisSpec`: an input BasisSpec object * `G::GraphSig`: an input GraphSig object ### Output Arguments * `f::Matrix{Float64}`: the reconstructed signal(s) * `GS::GraphSig`: the reconstructed GraphSig object """ function ghwt_synthesis(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec, G::GraphSig) # call the normal ghwt_synthesis f = ghwt_synthesis(dvec, GP, BS) # create a GraphSig object with the reconstructed data and return it with f. GS = deepcopy(G) # generate a new copy of G as GS replace_data!(GS, f) # then replace the graph signal field return f, GS end # of ghwt_synthesis (with G input) """ (dvecc2f, BSc2f) = ghwt_c2f_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix,2), useParent::Bool = true) Select the coarse-to-fine best basis from the matrix of GHWT expansion coefficients ### Input Arguments * `dmatrix::Array{Float64,3}`: the matrix of expansion coefficients * `GP::GraphPart`: an input GraphPart object * `cfspec::Any`: the specification of cost functional to be used (default = 1.0, i.e., 1-norm) * `flatten::Any`: the method for flattening vector-valued data to scalar-valued data (default = 1.0, i.e, 1-norm) * `useParent::Bool`: the flag to indicate if we update the selected best basis subspace to the parent when parent and child have the same cost (default = true) ### Output Arguments * `dvecc2f::Matrix{Float64}`: the vector of expansion coefficients corresponding to the coarse-to-fine best basis * `BSc2f::BasisSpec`: a BasisSpec object which specifies the coarse-to-fine best basis """ function ghwt_c2f_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix,2), useParent::Bool = true) # determine the cost functional to be used costfun = cost_functional(cfspec) # constants and dmatrix cleanup (N, jmax, fcols) = Base.size(dmatrix) if ~(1 <= j_start <= j_end <= jmax) error("j_start and j_end should satisfy the inequality 1 <= j_start <= j_end <= "*string(jmax)) end dmatrix[ abs.(dmatrix) .< 10^2 * eps() ] .= 0 # "flatten" dmatrix if fcols > 1 dmatrix0 = deepcopy(dmatrix) # keep the original dmatrix as dmatrix0 if !isnothing(flatten) dmatrix = dmatrix_flatten(dmatrix, flatten) end end ## Find the best-basis from the GHWT coarse-to-fine dictionary # allocate/initialize dvecc2f = dmatrix[:, j_end, 1] levlistc2f = j_end * ones(Int, N) # set the tolerance with sign tol = 10^4 * eps() * (1 - useParent * 2) # perform the basis search for j = (j_end - 1):-1:j_start regioncount = count(!iszero, GP.rs[:, j]) - 1 for r = 1:regioncount indr = GP.rs[r, j]:(GP.rs[r + 1, j]-1) ##### compute the cost of the current best basis costBB = costfun(dvecc2f[indr]) costNEW = costfun(dmatrix[indr, j, 1]) if costBB >= costNEW + tol #(dvecc2f[indr], levlistc2f[indr]) = bbchange(dmatrix[indr, j, 1], j) dvecc2f[indr] = dmatrix[indr, j, 1] levlistc2f[indr] .= j end end end #levlistc2f = Array{Int}(levlistc2f[ levlistc2f .!= 0 ]) levlistc2f = collect(enumerate(levlistc2f)) BSc2f = BasisSpec(levlistc2f, c2f = true, description = "GHWT c2f Best Basis") #levlist2levlengths!(GP, BSc2f) # if we flattened dmatrix, then "unflatten" the expansion coefficients if fcols > 1 dvecc2f = dmatrix2dvec(dmatrix0, GP, BSc2f) else dvecc2f = reshape(dvecc2f,(length(dvecc2f),1)) end # Return things return dvecc2f, BSc2f end # of function ghwt_c2f_bestbasis """ (dvecf2c, BSf2c) = ghwt_f2c_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix,2), useParent::Bool = true) Select the fine-to-coarse best basis from the matrix of GHWT expansion coefficients ### Input Arguments * `dmatrix::Array{Float64,3}`: the matrix of expansion coefficients * `GP::GraphPart`: an input GraphPart object * `cfspec::Any`: the specification of cost functional to be used (default: 1.0, i.e., 1-norm) * `flatten::Any`: the method for flattening vector-valued data to scalar-valued data (default: 1.0, i.e., 1-norm) * `useParent::Bool`: the flag to indicate if we update the selected best basis subspace to the parent when parent and child have the same cost (default = true) ### Output Arguments * `dvecf2c::Matrix{Float64}`: the vector of expansion coefficients corresponding to the fine-to-coarse best basis * `BSf2c::BasisSpec`: a BasisSpec object which specifies the fine-to-coarse best basis """ function ghwt_f2c_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix,2), useParent::Bool = true) # determine the cost functional to be used costfun = cost_functional(cfspec) # constants and dmatrix cleanup (N, jmax, fcols) = Base.size(dmatrix) if ~(1 <= j_start <= j_end <= jmax) error("j_start and j_end should satisfy the inequality 1 <= j_start <= j_end <= "*string(jmax)) end dmatrix[ abs.(dmatrix) .< 10^2 * eps() ] .= 0 # "flatten" dmatrix if fcols > 1 dmatrix0 = deepcopy(dmatrix) # keep the original dmatrix as dmatrix0 if !isnothing(flatten) dmatrix = dmatrix_flatten(dmatrix, flatten) end end ## Find the best-basis from the GHWT fine-to-coarse dictionary # generate the fine-to-coarse GraphPart fields and coefficient matrix dmatrixf2c = fine2coarse!(GP, dmatrix = dmatrix, coefp = true) # allocate/initialize dvecf2c = dmatrixf2c[:, j_end, 1] levlistf2c = j_end * ones(Int, N) # set the tolerance with sign tol = 10^4 * eps() * (1 - useParent * 2) # perform the basis search for j = (j_end - 1):-1:j_start regioncount = count(!iszero, GP.rsf2c[:, j]) - 1 for r = 1:regioncount indr = GP.rsf2c[r, j]:(GP.rsf2c[r + 1, j] - 1) ##### compute the cost of the current best basis costBB = costfun(dvecf2c[indr]) costNEW = costfun(dmatrixf2c[indr, j, 1]) if costBB >= costNEW + tol #(dvecf2c[indr], levlistf2c[indr]) = bbchange(dmatrixf2c[indr, j, 1], j) dvecf2c[indr] = dmatrixf2c[indr, j, 1] levlistf2c[indr] .= j end end end #levlistf2c = Array{Int}(levlistf2c[ levlistf2c .!= 0 ]) levlistf2c = collect(enumerate(levlistf2c)) BSf2c = BasisSpec(levlistf2c, c2f = false, description = "GHWT f2c Best Basis") #levlist2levlengths!(GP, BSf2c) # costf2c = costfun(dvecf2c) # if we flattened dmatrix, then "unflatten" the expansion coefficients if fcols > 1 dvecf2c = dmatrix2dvec(dmatrix0, GP, BSf2c) else dvecf2c = reshape(dvecf2c,(length(dvecf2c),1)) end # Return things return dvecf2c, BSf2c end # of function ghwt_f2c_bestbasis """ (dvec, BS) = ghwt_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Any, flatten::Any = 1.0) Select the overall best basis among the c2f and f2c best bases ### Input Arguments * `dmatrix::Array{Float64,3}`: the matrix of expansion coefficients * `GP::GraphPart`: an input GraphPart object * `cfspec::Any`: the specification of cost functional to be used (default: 1.0, i.e., 1-norm) * `flatten::Any`: the method for flattening vector-valued data to scalar-valued data (default: 1.0, i.e., 1-norm) ### Output Arguments * `dvec::Matrix{Float64}`: the vector of expansion coefficients corresponding to the best basis * `BS::BasisSpec`: a BasisSpec object which specifies the best basis """ function ghwt_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix,2)) costfun = cost_functional(cfspec) jmax = size(dmatrix,2) if ~(1 <= j_start <= j_end <= jmax) error("j_start and j_end should satisfy the inequality 1 <= j_start <= j_end <= "*string(jmax)) end # Select the c2f best basis (dvecc2f, BSc2f) = ghwt_c2f_bestbasis(dmatrix, GP, cfspec = cfspec, flatten = flatten, j_start = j_start, j_end = j_end) costc2f = costfun(dvecc2f) # Select the f2c best basis (dvecf2c, BSf2c) = ghwt_f2c_bestbasis(dmatrix, GP, cfspec = cfspec, flatten = flatten, j_start = jmax + 1 - j_end, j_end = jmax + 1 - j_start) costf2c = costfun(dvecf2c) # Compare the coarse-to-fine and fine-to-coarse best-bases if costc2f >= costf2c dvec = dvecf2c BS = BSf2c else dvec = dvecc2f BS = BSc2f end # Return things return dvec, BS end # of function ghwt_bestbasis """ function GHWT_jkl(GP::GraphPart, drow::Int, dcol::Int; c2f::Bool = true) Generate the (j,k,l) indices for the GHWT basis vector corresponding to the coefficient dmatrix(drow,dcol) ### Input Arguments * `GP`: a GraphPart object * `drow`: the row of the expansion coefficient * `dcol`: the column of the expansion coefficient ### Output Argument * `j`: the level index of the expansion coefficient * `k`: the subregion index of the expansion coefficient * `l`: the tag of the expansion coefficient """ function GHWT_jkl(GP::GraphPart, drow::Int, dcol::Int; c2f::Bool = true) if c2f j = dcol - 1 k = findfirst(GP.rs[:,dcol] .> drow) k -= 2 if isempty(GP.tag) ghwt_core!(GP) end l = GP.tag[drow,dcol] else jmax = size(GP.rs, 2) j = jmax - dcol IX = fine2coarse!(GP; indp = true) k = findfirst(GP.rs[:,j+1] .> IX[drow,dcol]) k -= 2 l = GP.tagf2c[drow,dcol] end return j,k,l end # of function GHWT_jkl end # of module GHWT
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
7434
module GHWT_2d include("utils.jl") using ..GraphSignal, ..GraphPartition, ..BasisSpecification, ..GHWT, LinearAlgebra, SparseArrays include("common.jl") export ghwt_analysis_2d, ghwt_bestbasis_2d, ghwt_synthesis_2d """ dmatrix = ghwt_analysis_2d(matrix::Array{Float64,2}, GProws::GraphPart, GPcols::GraphPart) For a matrix, equipped with row and column weight recursive partitionings and weight matrices, generate the redundant matrix of GHWT expansion coefficients. ### Input Arguments `matrix` the matrix to be analyzed `GProws` the recursive partitioning on the rows `GPcols` the recursive partitioning on the columns ### Output Arguments `dmatrix` the GHWT dictionary expansion coefficients Copyright 2019 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_analysis_2d(matrix::Array{Float64,2}, GProws::GraphPart, GPcols::GraphPart) if isempty(GProws.tag) ghwt_core!(GProws) end if isempty(GPcols.tag) ghwt_core!(GPcols) end matrix_re = matrix[GProws.ind, GPcols.ind] (N, jmax_row) = size(GProws.rs) N = N-1 # expand on the row direction (frows, fcols) = size(matrix_re) dmatrix = zeros((N,jmax_row,fcols)) dmatrix[:,jmax_row,:] = matrix_re ghwt_core!(GProws, dmatrix) dmatrix = reshape(dmatrix, (frows*jmax_row, fcols))' # expand on the column direction (N, jmax_col) = size(GPcols.rs) N = N - 1 dmatrix2 = zeros(N,jmax_col,size(dmatrix,2)) dmatrix2[:, jmax_col, :] = dmatrix ghwt_core!(GPcols, dmatrix2) dmatrix = reshape(dmatrix2, (fcols*jmax_col, frows*jmax_row))' return Array{Float64,2}(dmatrix) end """ dvec, BSrows, BScols = ghwt_2d_bestbasis(matrix::Array{Float64,2},GProws::GraphPart,GPcols::GraphPart, costfun_rows::Any = 1.0, costfun_cols::Any = 1.0, flatten_rows::Any = 1.0, flatten_cols::Any = 1.0) For a matrix, equipped with row and column weight recursive partitionings and weight matrices, generate the (non-redundant) matrix of GHWT expansion coefficients, using the best basis algorithm to select best bases for the rows and columns ### Input Argument * `matrix` the matrix to be analyzed * `GProws` the recursive partitioning on the rows * `GPcols` the recursive partitioning on the columns * `costfun_rows` the cost functional to be used for the rows * `costfun_cols` the cost functional to be used for the columns * `flatten_rows` the method for flattening vector-valued data to scalar-valued data for the rows * `flatten_cols` the method for flattening vector-valued data to scalar-valued data for the columns ### Output Argument * `dvec` the GHWT expansion coefficients (not redundant) * `BSrows` the best basis on the rows * `BScols` the best basis on the columns Copyright 2019 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_bestbasis_2d(matrix::Array{Float64,2},GProws::GraphPart,GPcols::GraphPart; costfun_rows::Any = 1.0, costfun_cols::Any = 1.0, flatten_rows::Any = 1.0, flatten_cols::Any = 1.0) # generate GraphSig objects for the matrix rows,cols = size(matrix) Grows = GraphSig(spzeros(rows,rows),f = matrix) Gcols = GraphSig(spzeros(cols,cols),f = Matrix{Float64}(matrix')) # analyze the data matrix using the rows dmatrix = ghwt_analysis!(Grows, GP = GProws) # analyze the data matrix using the columns dmatrix2 = ghwt_analysis!(Gcols, GP = GPcols) # find the row and column best bases dvec,BSrows = ghwt_bestbasis(dmatrix,GProws,cfspec = costfun_rows,flatten = flatten_rows) ~,BScols = ghwt_bestbasis(dmatrix2,GPcols,cfspec = costfun_cols,flatten = flatten_cols) # analyze the row best-basis coefficient matrix using the columns Gcols.f = Matrix{Float64}(dvec') dmatrix = ghwt_analysis!(Gcols, GP = GPcols) # extract the col best-basis coefficients dvec = Matrix{Float64}(dmatrix2dvec(dmatrix, GPcols, BScols)') return dvec, BSrows, BScols end """ dvec = ghwt_2d_dmatrix2dvec(matrix::Array{Float64,2},BSrows::BasisSpec,BScols::BasisSpec) For a matrix, equipped with row and column weight recursive partitionings and weight matrices, generate the (non-redundant) matrix of GHWT expansion coefficients, using the best basis algorithm to select best bases for the rows and columns ### Input Argument * `matrix` the matrix to be analyzed * `GProws` the recursive partitioning on the rows * `GPcols` the recursive partitioning on the columns ### Output Argument * `dvec` the GHWT expansion coefficients (not redundant) Copyright 2019 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_2d_haar(matrix::Array{Float64,2},GProws::GraphPart,GPcols::GraphPart) # generate GraphSig objects for the matrix rows,cols = size(matrix) Grows = GraphSig(spzeros(rows,rows),f = matrix) Gcols = GraphSig(spzeros(cols,cols),f = Matrix{Float64}(matrix')) # analyze the data matrix using the rows dmatrix = ghwt_analysis!(Grows, GP = GProws) # analyze the data matrix using the columns #dmatrix2 = ghwt_analysis!(Gcols, GP = GPcols) # find the row and column best bases #BH=bs_haar(GP) #dvec=dmatrix2dvec(dc2f, GP, BH) BSrows = bs_haar(GProws) dvec = dmatrix2dvec(dmatrix, GProws, BSrows) BScols = bs_haar(GPcols) #dvec,BSrows = ghwt_bestbasis(dmatrix,GProws,cfspec = costfun_rows,flatten = flatten_rows) #~,BScols = ghwt_bestbasis(dmatrix2,GPcols,cfspec = costfun_cols,flatten = flatten_cols) # analyze the row best-basis coefficient matrix using the columns Gcols.f = Matrix{Float64}(dvec') dmatrix = ghwt_analysis!(Gcols, GP = GPcols) # extract the col best-basis coefficients dvec = Matrix{Float64}(dmatrix2dvec(dmatrix, GPcols, BScols)') return dvec, BSrows, BScols end """ matrix = ghwt_synthesis_2d(dvec::Matrix{Float64},GProws::GraphPart,GPcols::GraphPart,BSrows::BasisSpec,BScols::BasisSpec) Given a vector of GHWT expansion coefficients and info about the graph partitioning and the choice of basis, reconstruct the signal ### Input Arguments * `dvec` the expansion coefficients corresponding to the chosen basis * `GProws` the recursive partitioning on the rows * `GPcols` the recursive partitioning on the columns * `BSrows` the best basis on the rows * `BScols` the best basis on the columns ### Output Arguments * matrix the reconstructed matrix Copyright 2019 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_synthesis_2d(dvec::Matrix{Float64},GProws::GraphPart,GPcols::GraphPart,BSrows::BasisSpec,BScols::BasisSpec) # reconstruct dvec = ghwt_synthesis(Matrix{Float64}(dvec'), GPcols, BScols) matrix = ghwt_synthesis(Matrix{Float64}(dvec'), GProws, BSrows) return matrix end end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
23875
""" ind,rse,IND = PartitionTreeMatrixDhillon_QuadTree(matrix,jmax) Perform the quadtree partition of matrix. ### Input Arguments * `matrix`: The matrix to be partitioned * `jmax`: Specify the max level of partitioning the matrix ### Output Arguments * `ind`: Vector with the same length as length(matrix[:]), indicate the order of matrix after partition. * `rse`: Region start and end. Each pair represents the start and end of a region in the matrix, corresponding to one node in the quadtree * `IND`: IND[i] indicate the order of matrix after iteration i. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function PartitionTreeMatrixDhillon_QuadTree(matrix,jmax) # 0.Preliminary # Constants rows,cols = size(matrix); N = rows*cols ind = Matrix{Int64}(reshape(1:N,rows,cols)) IND = zeros(rows,cols,jmax); IND[:,:,1] = ind; # region starts & ends rse = Vector{Vector{Int64}}(jmax) rse[1] = [1,N]; # 1. Partition the graph to yield rse, ind and jmax j=1; regioncount = 0; while j<=jmax-1 # add a column for j+1, if necessary rr = 1#for tracking the child regions rse[j+1] = zeros(Int64,4*length(rse[j])) for r = 1:2:(length(rse[j]) - 1) rs_rows,rs_cols = ind2sub((rows,cols),rse[j][r]) re_rows,re_cols = ind2sub((rows,cols),rse[j][r+1]) n_rows = re_rows-rs_rows+1 n_cols = re_cols-rs_cols+1 indrs = ind[rs_rows:re_rows,rs_cols:re_cols] if n_rows > 1 && n_cols > 1 # compute the left and right singular vectors u_rows,v_cols = second_largest_singular_vectors(reshape(matrix[indrs[:]],n_rows,n_cols)) # partition the current region pm,_ = partition_fiedler(SparseMatrixCSC{Float64,Int}(ones(1,1)),v = vcat(u_rows, v_cols)) pm_rows = pm[1:n_rows] pm_cols = pm[n_rows+1:end] # determine the number of points in child region 1 n1_rows = sum(pm_rows .> 0); n1_cols = sum(pm_cols .> 0); # update the indexing ind[rs_rows:re_rows,rs_cols:re_cols] = indrs[vcat(find(pm_rows .> 0),find(pm_rows.<=0)),vcat(find(pm_cols.>0),find(pm_cols.<=0))] if !(n1_rows==0 || n1_rows == n_rows) && !(n1_cols==0 ||n1_cols==n_cols) child_rows = [rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows, rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows]; child_cols = [rs_cols, rs_cols+n1_cols-1, rs_cols, rs_cols+n1_cols-1, rs_cols+n1_cols, re_cols, rs_cols+n1_cols, re_cols]; for k = 1:8 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 8 elseif (n1_rows == 0 || n1_rows == n_rows) && !(n1_cols == 0 || n1_cols == n_cols) child_rows = [rs_rows, re_rows, rs_rows, re_rows]; child_cols = [rs_cols, rs_cols+n1_cols-1, rs_cols+n1_cols, re_cols]; for k = 1:4 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 4 elseif (n1_cols == 0 || n1_cols == n_cols) && !(n1_rows == 0 || n1_rows == n_rows) child_rows = [rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows]; child_cols = [rs_cols, re_cols, rs_cols, re_cols]; for k = 1:4 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 4 else rse[j+1][rr:rr+1] = rse[j][r:r+1] rr = rr + 2 end elseif n_rows == 1 && n_cols > 1 #no bisection on rows pm_cols,_ = partition_fiedler(SparseMatrixCSC{Float64,Int}(ones(1,1)),v = matrix[indrs[:]]) n1_cols = sum(pm_cols .> 0); ind[rs_rows:re_rows,rs_cols:re_cols] = indrs[:,vcat(find(pm_cols.>0),find(pm_cols.<=0))] child_rows = [rs_rows, re_rows, rs_rows, re_rows]; child_cols = [rs_cols, rs_cols+n1_cols-1, rs_cols+n1_cols, re_cols]; for k = 1:4 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 4 elseif n_rows > 1 && n_cols == 1 #no bisection on cols pm_rows,_ = partitio_fiedler(SparseMatrixCSC{Float64,Int}(ones(1,1)),v = matrix[indrs[:]]) n1_rows = sum(pm_rows .> 0); ind[rs_rows:re_rows,rs_cols:re_cols] = indrs[vcat(find(pm_rows .> 0),find(pm_rows.<=0)),:] child_rows = [rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows]; child_cols = [rs_cols, re_cols, rs_cols, re_cols]; for k = 1:4 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 4 else rse[j+1][rr:rr+1] = rse[j][r:r+1] rr = rr + 2 end end j = j+1 rse[j] = rse[j][rse[j].!=0] IND[:,:,j] = ind end return ind,rse,IND end """ u,v = second_largest_singular_vectors(A::Matrix{Float64}) Compute the second largest left and right singular vectors of matrix. ### Input Arguments * `A`: The matrix of which the singular vectors will be computed. ### Output Arguments * `u`: Second largest left singular vector. * `v`: Second largest right singular vector. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function second_largest_singular_vectors(A::Matrix{Float64}) #Compute the second largest left and right singular vectors of An = D1^-0.5*A*D2^-0.5 rows,cols = size(A) # compute D1 and D2 and make sure there are no zeros D1 = sum(A,2) D1[D1 .== 0] = maximum([0.01, minimum(D1[D1 .> 0])/10]) D2 = sum(A,1) D2[D2 .== 0] = maximum([0.01, minimum(D2[D2 .> 0])/10]) u,_,v = svd(Diagonal(D1[:].^(-0.5))*A*Diagonal(D2[:].^(-0.5))) # extract the 2nd singular vectors and multiply by D_i^-0.5 u = Diagonal(D1[:].^-0.5)*u[:,2] v = Diagonal(D2[:].^-0.5)*v[:,2] return u,v end """ BBmatrix, BBmatrix_ind, tag, dmatrix = GHWT_Matrix2D_Analysis_BestBasis(matrix::Matrix{Float64},ind::Matrix{Int64} ,rse::Vector{Array{Int64,1}}) Compute the expanding coeffcients of all levels and search for the best-basis given the partition quadtree of matrix. ### Input Arguments * `matrix`: The matrix which will be analyzed. * `ind`: Vector with the same length as length(matrix[:]), indicate the order of matrix after partition. * `rse`: Region start and end. Each pair represents the start and end of a region in the matrix, corresponding to one node in the quadtree ### Output Arguments * `BBmatrix`: Coefficients of the best-basis. * `BBmatrix_ind`: Location of the best-basis in dmatrix. * `tag`: Tag information of the expanding coefficients. * `dmatrix`: The expanding coefficients on all levels. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function GHWT_Matrix2D_Analysis_BestBasis(matrix::Matrix{Float64},ind::Matrix{Int64} ,rse::Vector{Array{Int64,1}}) # cost functional costfun = function(x) norm(x[:],1) end # constants rows,cols = size(matrix); #tol = 10^4*eps() # 1. Recursively partition the rows and columns of the matrix in a coupled manner #ind,rse,_ = PartitionTreeMatrixDhillon_QuadTree_ys(matrix) jmax = length(rse) # 2. Analyze the matrix and perform the best basis search dmatrix = zeros(rows,cols,jmax) dmatrix[:,:,jmax] = matrix[ind] tag = zeros(Int64,rows,cols,jmax) for r = 1:2:length(rse[jmax]) if rse[jmax][r] != rse[jmax][r+1] rs_rows,rs_cols = ind2sub((rows,cols),rse[jmax][r]) re_rows,re_cols = ind2sub((rows,cols),rse[jmax][r+1]) tag[rs_rows:re_rows,rs_cols:re_cols,jmax] = reshape(0:(re_rows-rs_rows+1)*(re_cols-rs_cols+1)-1,re_rows-rs_rows+1,re_cols-rs_cols+1) average = sum(dmatrix[rs_rows:re_rows,rs_cols:re_cols,jmax])/sqrt((re_rows-rs_rows+1)*(re_cols-rs_cols+1)) dmatrix[rs_rows:re_rows,rs_cols:re_cols,jmax] = 0 dmatrix[rs_rows,rs_cols,jmax] = average end end #best basis BBmatrix = dmatrix[:,:,jmax] BBmatrix_ind = jmax*ones(Int64,rows,cols) for j = jmax-1:-1:1 rr = 1; for r = 1:2:length(rse[j]) rs_rows,rs_cols = ind2sub((rows,cols),rse[j][r]) re_rows,re_cols = ind2sub((rows,cols),rse[j][r+1]) # the row indices being considered indrs_rows = rs_rows:re_rows # the column indices being considered indrs_cols = rs_cols:re_cols n_rows = re_rows-rs_rows+1 n_cols = re_cols-rs_cols+1 #copy of children if rse[j][r+1] == rse[j+1][rr+1] dmatrix[indrs_rows,indrs_cols,j] = dmatrix[indrs_rows,indrs_cols,j+1] tag[indrs_rows,indrs_cols,j] = tag[indrs_rows,indrs_cols,j+1] rr = rr+2 #copy of two childern elseif rse[j][r+1] == rse[j+1][rr+3] a,b = zeros(Int64,4), zeros(Int64,4) for k = 1:4 a[k],b[k] = ind2sub((rows,cols),rse[j+1][rr+k-1]) end region1 = dmatrix[a[1]:a[2],b[1]:b[2],j+1] region2 = dmatrix[a[3]:a[4],b[3]:b[4],j+1] tag1 = tag[a[1]:a[2],b[1]:b[2],j+1] tag2 = tag[a[3]:a[4],b[3]:b[4],j+1] region_vec, tag_vec = twoblockcombine(region1[:],region2[:],tag1[:],tag2[:]); tag[indrs_rows,indrs_cols,j] = reshape(tag_vec,n_rows,n_cols); dmatrix[indrs_rows,indrs_cols,j] = reshape(region_vec,n_rows,n_cols) rr = rr + 4 elseif rse[j][r+1] == rse[j+1][rr+7] a,b = zeros(Int64,8), zeros(Int64,8) for k = 1:8 a[k],b[k] = ind2sub((rows,cols),rse[j+1][rr+k-1]) end region11 = dmatrix[a[1]:a[2],b[1]:b[2],j+1] region21 = dmatrix[a[3]:a[4],b[3]:b[4],j+1] tag11 = tag[a[1]:a[2],b[1]:b[2],j+1] tag21 = tag[a[3]:a[4],b[3]:b[4],j+1] region12 = dmatrix[a[5]:a[6],b[5]:b[6],j+1] region22 = dmatrix[a[7]:a[8],b[7]:b[8],j+1] tag12 = tag[a[5]:a[6],b[5]:b[6],j+1] tag22 = tag[a[7]:a[8],b[7]:b[8],j+1] region_vec_1, tag_vec_1 = twoblockcombine(region11[:],region21[:],tag11[:],tag21[:]) region_vec_2, tag_vec_2 = twoblockcombine(region12[:],region22[:],tag12[:],tag22[:]) region_vec, tag_vec = twoblockcombine(region_vec_1,region_vec_2,tag_vec_1,tag_vec_2) tag[indrs_rows,indrs_cols,j] = reshape(tag_vec, n_rows,n_cols) dmatrix[indrs_rows,indrs_cols,j] = reshape(region_vec,n_rows,n_cols) rr = rr + 8 end #Obtaining BBmatrix if costfun(BBmatrix[indrs_rows,indrs_cols]) > costfun(dmatrix[indrs_rows,indrs_cols,j]) BBmatrix[indrs_rows,indrs_cols] = dmatrix[indrs_rows,indrs_cols,j] BBmatrix_ind[indrs_rows,indrs_cols] = j; end end end return BBmatrix, BBmatrix_ind, tag, dmatrix end """ region, tag = twoblockcombine(region1::Vector{Float64}, region2::Vector{Float64}, tag1::Vector{Int64}, tag2::Vector{Int64}) Compute the coefficients of coarser basis-vectors after combining finer basis-vectors supported on two sub-regions. ### Input Arguments * `region1`: The coeffcient of finer basis-vectors supported on region 1. * `tag1`: The tag information of finer basis-vectors supported on region 1. * `region2`: The coeffcient of finer basis-vectors supported on region 2. * `tag2`: The tag information of finer basis-vectors supported on region 2. ### Output Arguments * `region`: The coeffcient of coarser basis-vectors supported on region 1 and region 2. * `tag`: The tag information of coarser basis-vectors supported on region 1 and region 2. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function twoblockcombine(region1::Vector{Float64}, region2::Vector{Float64}, tag1::Vector{Int64}, tag2::Vector{Int64}) # the number of points in the first subregion n1 = length(region1) # the number of points in the second subregion n2 = length(region2) n = n1+n2 region = zeros(n) tag = zeros(Int64,n) ### SCALING COEFFICIENT (n > 1) region[1] = ( sqrt(n1)*region1[1] + sqrt(n2)*region2[1] )/sqrt(n) tag[1] = 0 ### HAAR-LIKE COEFFICIENT region[2] = ( sqrt(n2)*region1[1] - sqrt(n1)*region2[1] )/sqrt(n); tag[2] = 1 ### WALSH-LIKE COEFFICIENTS # sweep through the coefficients in subregion 1 and subregion 2 # the index of the new coefficient(s) to be created on level j parent = 3 # the index of the current coefficients in subregions 1 and 2 child1 = 2 child2 = 2 while parent <= n # no matching coefficient (use subregion 1) if child1 <= n1 && (child2 == n2+1 || tag1[child1] < tag2[child2]) region[parent] = region1[child1] tag[parent] = 2*tag1[child1] child1 = child1+1; parent = parent+1; # no matching coefficient (use subregion 2) elseif child2 <=n2 && (child1 == n1+1 || tag2[child2] < tag1[child1]) region[parent] = region2[child2] tag[parent] = 2*tag2[child2] child2 = child2+1 parent = parent+1 # matching coefficients else region[parent] = ( region1[child1] + region2[child2] )/sqrt(2) tag[parent] = 2*tag[child1] region[parent+1] = ( region1[child1] - region2[child2] )/sqrt(2) tag[parent+1] = 2*tag[child1]+1 child1 = child1+1 child2 = child2+1 parent = parent+2 end end return region, tag end """ matrix_r = GHWT_Matrix2D_Analysis_Synthesis(BBmatrix::Matrix{Float64},BBmatrix_ind::Matrix{Int64},tag::Array{Int64,3} ,rse::Vector{Array{Int64,1}}) Synthesize the matrix given coefficients of selected basis-vectors. ### Input Arguments * `BBmatrix`: Coefficients of the best-basis. * `BBmatrix_ind`: Location of the best-basis in dmatrix. * `tag`: Tag information of the expanding coefficients. * `rse`: Region start and end. Each pair represents the start and end of a region in the matrix, corresponding to one node in the quadtree. ### Output Arguments * `matrix_r`: The synthesized matrix. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function GHWT_Matrix2D_Analysis_Synthesis(BBmatrix::Matrix{Float64},BBmatrix_ind::Matrix{Int64},tag::Array{Int64,3} ,rse::Vector{Array{Int64,1}}) costfun = function(x) norm(x[:],1) end # constants rows,cols = size(BBmatrix); #tol = 10^4*eps() jmax = length(rse) cmatrix = zeros(rows,cols,jmax); for i = 1:rows for j = 1:cols cmatrix[i,j,BBmatrix_ind[i,j]] = BBmatrix[i,j]; end end for j = 1:1:jmax-1 rr = 1 for r = 1:2:length(rse[j]) rs_rows,rs_cols = ind2sub((rows,cols),rse[j][r]) re_rows,re_cols = ind2sub((rows,cols),rse[j][r+1]) if rse[j][r+1] == rse[j+1][rr+1] if countnz(cmatrix[rs_rows:re_rows,rs_cols:re_cols,j+1]) == 0 && countnz(cmatrix[rs_rows:re_rows,rs_cols:re_cols,j]) > 0 cmatrix[rs_rows:re_rows,rs_cols:re_cols,j+1] = cmatrix[rs_rows:re_rows,rs_cols:re_cols,j] end rr = rr + 2 elseif rse[j][r+1] == rse[j+1][rr+3] if countnz(cmatrix[rs_rows:re_rows,rs_cols:re_cols,j+1]) == 0 && countnz(cmatrix[rs_rows:re_rows,rs_cols:re_cols,j]) > 0 a,b = zeros(Int64,4), zeros(Int64,4) for k = 1:4 a[k],b[k] = ind2sub((rows,cols),rse[j+1][rr+k-1]) end region = cmatrix[rs_rows:re_rows,rs_cols:re_cols,j] tag1 = tag[a[1]:a[2],b[1]:b[2],j+1] tag2 = tag[a[3]:a[4],b[3]:b[4],j+1] region1_vec, region2_vec = twoblocksplit(region[:],tag1[:],tag2[:]); cmatrix[a[1]:a[2],b[1]:b[2],j+1] = reshape(region1_vec,a[2]-a[1]+1,b[2]-b[1]+1) cmatrix[a[3]:a[4],b[3]:b[4],j+1] = reshape(region2_vec,a[4]-a[3]+1,b[4]-b[3]+1) end rr = rr + 4 else if countnz(cmatrix[rs_rows:re_rows,rs_cols:re_cols,j+1]) == 0 && countnz(cmatrix[rs_rows:re_rows,rs_cols:re_cols,j]) > 0 a,b = zeros(Int64,8), zeros(Int64,8) for k = 1:8 a[k],b[k] = ind2sub((rows,cols),rse[j+1][rr+k-1]) end tag11 = tag[a[1]:a[2],b[1]:b[2],j+1] tag21 = tag[a[3]:a[4],b[3]:b[4],j+1] tag12 = tag[a[5]:a[6],b[5]:b[6],j+1] tag22 = tag[a[7]:a[8],b[7]:b[8],j+1] tag11 = tag11[:] tag21 = tag21[:] tag12 = tag12[:] tag22 = tag22[:] tag1 = twoblockcombine_tag(tag11,tag21) tag2 = twoblockcombine_tag(tag12,tag22) region = cmatrix[rs_rows:re_rows,rs_cols:re_cols,j] region1_vec,region2_vec = twoblocksplit(region[:], tag1,tag2) region11,region21 = twoblocksplit(region1_vec,tag11,tag21) region12,region22 = twoblocksplit(region2_vec,tag12,tag22) cmatrix[a[1]:a[2],b[1]:b[2],j+1] = reshape(region11,a[2]-a[1]+1,b[2]-b[1]+1) cmatrix[a[3]:a[4],b[3]:b[4],j+1] = reshape(region21,a[4]-a[3]+1,b[4]-b[3]+1) cmatrix[a[5]:a[6],b[5]:b[6],j+1] = reshape(region12,a[6]-a[5]+1,b[6]-b[5]+1) cmatrix[a[7]:a[8],b[7]:b[8],j+1] = reshape(region22,a[8]-a[7]+1,b[8]-b[7]+1) end rr = rr + 8 end end end matrix_r = cmatrix[:,:,end] for r = 1:2:length(rse[jmax]) if rse[jmax][r] != rse[jmax][r+1] rs_rows,rs_cols = ind2sub((rows,cols),rse[j][r]) re_rows,re_cols = ind2sub((rows,cols),rse[j][r+1]) matrix_r[rs_rows:re_rows,rs_cols:re_cols] = matrix_r[rs_rows,rs_cols]/sqrt((re_rows-rs_rows+1)*(re_cols-rs_cols+1)) end end return matrix_r end """ tag = twoblockcombine_tag(tag1::Vector{Int64},tag2::Vector{Int64}) Compute the tag information of coarser basis-vectors after combining finer basis-vectors supported on two sub-regions. ### Input Arguments * `tag1`: The tag information of finer basis-vectors supported on region 1. * `tag2`: The tag information of finer basis-vectors supported on region 2. ### Output Arguments * `tag`: The tag information of coarser basis-vectors supported on region 1 and region 2. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function twoblockcombine_tag(tag1::Vector{Int64},tag2::Vector{Int64}) # the number of points in the first subregion n1 = length(tag1) # the number of points in the second subregion n2 = length(tag2) n = n1+n2 tag = zeros(Int64,n) ### SCALING COEFFICIENT (n > 1) tag[1] = 0 ### HAAR-LIKE COEFFICIENT tag[2] = 1 ### WALSH-LIKE COEFFICIENTS # sweep through the coefficients in subregion 1 and subregion 2 # the index of the new coefficient(s) to be created on level j parent = 3 # the index of the current coefficients in subregions 1 and 2 child1 = 2 child2 = 2 while parent <= n # no matching coefficient (use subregion 1) if child1 <= n1 && (child2 == n2+1 || tag1[child1] < tag2[child2]) tag[parent] = 2*tag1[child1] child1 = child1+1 parent = parent+1 # no matching coefficient (use subregion 2) elseif child2 <=n2 && (child1 == n1+1 || tag2[child2] < tag1[child1]) tag[parent] = 2*tag2[child2] child2 = child2+1 parent = parent+1 # matching coefficients else tag[parent] = 2*tag[child1] tag[parent+1] = 2*tag[child1]+1 child1 = child1+1 child2 = child2+1 parent = parent+2 end end return tag end """ region1,region2 = twoblocksplit(region::Matrix{Float64}, tag1::Vector{Int64}, tag2::Vector{Int64}) Compute the coefficients of finer basis-vectors supported on two sub-regions given the coeffcients of coarser basis-vectors supported on both regions. ### Input Arguments * `region`: The coeffcient of coarser basis-vectors supported on region 1 and region 2. * `tag1`: The tag information of finer basis-vectors supported on region 1. * `tag2`: The tag information of finer basis-vectors supported on region 2. ### Output Arguments * `region1`: The coeffcient of finer basis-vectors supported on region 1. * `region2`: The coeffcient of finer basis-vectors supported on region 2. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function twoblocksplit(region::Matrix{Float64}, tag1::Vector{Int64}, tag2::Vector{Int64}) # the number of points in the first subregion n1 = length(tag1) # the number of points in the second subregion n2 = length(tag2) n = n1+n2 region1 = zeros(n1) region2 = zeros(n2); ### SCALING COEFFICIENT (n > 1) region1[1] = ( sqrt(n1)*region[1] + sqrt(n2)*region[2] )/sqrt(n); ### HAAR-LIKE COEFFICIENT region2[1] = ( sqrt(n2)*region[1] - sqrt(n1)*region[2] )/sqrt(n); ### WALSH-LIKE COEFFICIENTS # sweep through the coefficients in subregion 1 and subregion 2 # the index of the new coefficient(s) to be created on level j parent = 3 # the index of the current coefficients in subregions 1 and 2 child1 = 2 child2 = 2 while parent <= n # no matching coefficient (use subregion 1) if child1 <= n1 && (child2 == n2+1 || tag1[child1] < tag2[child2]) region1[child1] = region[parent] child1 = child1+1 parent = parent+1 # no matching coefficient (use subregion 2) elseif child2 <=n2 && (child1 == n1+1 || tag2[child2] < tag1[child1]) region2[child2] = region[parent] child2 = child2+1 parent = parent+1 # matching coefficients else region1[child1] = ( region[parent] + region[parent+1] )/sqrt(2) region2[child2] = ( region[parent] - region[parent+1] )/sqrt(2) child1 = child1+1 child2 = child2+1 parent = parent+2 end end return region1,region2 end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
11844
module GHWT_tf_1d include("utils.jl") using ..GraphSignal, ..GraphPartition, ..BasisSpecification, LinearAlgebra include("common.jl") export ghwt_tf_bestbasis, eghwt_bestbasis """ coeffdict = tf_init(dmatrix::Matrix{Float64},GP::GraphPart) Store the expanding coeffcients from matrix into a list of dictionary (inbuilt hashmap in Julia) ### Input Arguments * `dmatrix`: The expanding GHWT coefficients of all levels corresponding to input GP * `GP::GraphPart`: an input GraphPart object ### Output Arguments * `coeffdict`: The expanding GHWT coeffcients stored in a list of "dictionary" (inbuilt hashmap in Julia), * `coeffdict`: The entry `coeffdict[j][(k,l)]` corresponds to the coefficient of basis-vector on level j with region k and tag l. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function tf_init(dmatrix::Matrix{Float64},GP::GraphPart) # Obtain the tag information tag = convert(Array{Int,2},GP.tag) # Obtain the region information tag_r = convert(Array{Int,2},rs_to_region(GP.rs, GP.tag)) (m,n) = size(dmatrix) # Initialize coeffdict coeffdict = Array{Dict{Tuple{Int,Int},Float64}}(undef, n) # Fill in the values with the rule that `coeffdict[j][(k,l)]` represents # the coefficient of basis-vector on level j with region k and tag l. for i = 1:n coeffdict[i]= Dict{Tuple{Int,Int},Float64}((tag_r[j,i],tag[j,i]) => dmatrix[j,i] for j=1:m) end return coeffdict end """ coeffdict_new,tag_tf = tf_core_new(coeffdict::Array{Dict{Tuple{Int,Int},Float64},1}) One forward iteration of time-frequency adapted GHWT method. For each entry in `coeffdict_new`, we compare two (or one) entries in 'coeffdict' on time-direction and two (or one) entries in 'coeffdict' on frequency-direction. Those two groups reprensent the same subspace. We compare the cost-functional value of them and choose the smaller one as a new entry in 'coeffdict_new'. ### Input Arguments * `coeffdict`: The entries of which reprensents the cost functional value of some basis-vectors' coefficients. ### Output Arguments * `coeffdict_new`: The entries of which represents the cost functional value of some basis-vectors' coefficients * `tag_tf`: Indicating whether the time-direction (0) or frequency direction (1) was chosen for each entry in coeffdict_new. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function tf_core_new(coeffdict::Array{Dict{Tuple{Int,Int},Float64},1}) # We choose '1-norm' as the optional cost functional costfun = cost_functional(1) jmax = length(coeffdict) # Initialization coeffdict_new = Array{Dict{Tuple{Int,Int},Float64}}(undef, jmax-1) tag_tf = Array{Dict{Tuple{Int,Int},Bool}}(undef, jmax-1) # Iterate through levels for j = 1:(jmax-1) # the temporary dictionary, which will be the j-th level of `coeffdict_new` temp_coeff = Dict{Tuple{Int,Int},Float64}() # the temporary dictionary, which will be the j-th level of 'tag_tf' temp_tf = Dict{Tuple{Int,Int},Bool}() # iterate through the entries in coeffdict on level j for key in keys(coeffdict[j]) # coeffdict[j][k,l] represent the entry on level j with region k and tag l k = key[1] # region index l = key[2] # tag index # only look at the entry with even tag l to avoid duplication if l%2 == 0 # search for the (j,k,l+1) entry. # the (j,k,l) and (j,k,l+1) span the same subspace as (j+1,2*k,l/2) and (j+1,2*k+1,l/2) # (j,k,l) and (j,k,l+1) are `frequency-direction` # (j,k,l) and (j,k,l+1) are `time-direction` if haskey(coeffdict[j],(k,l+1)) # check for degenerate case ((j,k,l+1) doesn't exist) freqcos = costfun([coeffdict[j][(k,l)],coeffdict[j][(k,l+1)]]) else freqcos = costfun([coeffdict[j][(k,l)]]) end if ~haskey(coeffdict[j+1],(2*k,l/2)) # check for degenerate case ((j+1,2*k,l/2) or (j+1,2*k+1,l/2) doesn't exist) timecos = costfun([coeffdict[j+1][(2*k+1,l/2)]]) elseif ~haskey(coeffdict[j+1],(2*k+1,l/2)) timecos = costfun([coeffdict[j+1][(2*k,l/2)]]) else timecos = costfun([coeffdict[j+1][(2*k+1,l/2)],coeffdict[j+1][(2*k,l/2)]]) end # compare the cost-functional value and record into 'tag_tf' if timecos <= freqcos temp_coeff[(k,l/2)] = timecos temp_tf[(k,l/2)] = false else temp_coeff[(k,l/2)] = freqcos temp_tf[(k,l/2)] = true end end end coeffdict_new[j] = temp_coeff tag_tf[j] = temp_tf end return coeffdict_new,tag_tf end """ tag_tf_b_new = tf_basisrecover_new(tag_tf_b::Array{Dict{Tuple{Int,Int},Bool}},tag_tf_f::Array{Dict{Tuple{Int,Int},Bool}}) One backward iteration of time-frequency adapted GHWT method to recover the best-basis from the `tag_tf`s recorded. ### Input Arguments * `tag_tf_b`: The `dictionary` recording the time-or-frequency information on some iteration 'i' in the main algorithm * `tag_tf_f`: The `dictionary` recording the time-or-frequency information on some iteration 'i+1' in the main algorithm ### Output Arguments * `tag_tf_b_new`: The updated 'tag_tf_b'. Eventually the 'tag_tf' on iteration 1 will represent the selected best-basis Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function tf_basisrecover_new(tag_tf_b::Array{Dict{Tuple{Int,Int},Bool}},tag_tf_f::Array{Dict{Tuple{Int,Int},Bool}}) # Initialization jmax = length(tag_tf_b) #tag_tf_b_new = Array{Dict{Tuple{Int,Int},Bool}}(jmax) tag_tf_b_new = Array{Dict{Tuple{Int,Int},Bool}}(undef, jmax) for j = 1:jmax tag_tf_b_new[j] = Dict{Tuple{Int,Int},Bool}() end # Iterate on the levels for j = 1:(jmax-1) for key in keys(tag_tf_f[j]) k = key[1] l = key[2] # The entries on frequency-direction are selected if tag_tf_f[j][(k,l)] == true if ~haskey(tag_tf_b[j],(k,2*l)) tag_tf_b_new[j][(k,2*l+1)] = tag_tf_b[j][(k,2*l+1)] elseif ~haskey(tag_tf_b[j],(k,2*l+1)) tag_tf_b_new[j][(k,2*l)] = tag_tf_b[j][(k,2*l)] else tag_tf_b_new[j][(k,2*l)] = tag_tf_b[j][(k,2*l)] tag_tf_b_new[j][(k,2*l+1)] = tag_tf_b[j][(k,2*l+1)] end else # The entries on time-direction are selected if ~haskey(tag_tf_b[j+1],(2*k,l)) tag_tf_b_new[j+1][(2*k+1,l)] = tag_tf_b[j+1][(2*k+1,l)] elseif ~haskey(tag_tf_b[j+1],(2*k+1,l)) tag_tf_b_new[j+1][(2*k,l)] = tag_tf_b[j+1][(2*k,l)] else tag_tf_b_new[j+1][(2*k+1,l)] = tag_tf_b[j+1][(2*k+1,l)] tag_tf_b_new[j+1][(2*k,l)] = tag_tf_b[j+1][(2*k,l)] end end end end return tag_tf_b_new end """ (dvec, BS) = ghwt_tf_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Float64 = 1.0, flatten::Any = 1.0) Implementation of time-frequency adapted GHWT method = eGHWT. Modified from the algorithm in the paper: "A Fast Algorithm for Adapted Time Frequency Tilings" by Christoph M. Thiele and Lars F. Villemoes. ### Input Arguments * `dmatrix::Array{Float64,3}`: the matrix of expansion coefficients * `GP::GraphPart`: an input GraphPart object * `cfspec::Any`: the specification of cost functional to be used (default: 1.0, i.e., 1-norm) * `flatten::Any`: the method for flattening vector-valued data to scalar-valued data (default: 1.0, i.e., 1-norm) ### Output Arguments * `dvec::Matrix{Float64}`: the vector of expansion coefficients corresponding to the eGHWT best basis * `BS::BasisSpec`: a BasisSpec object which specifies the eGHWT best basis Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_tf_bestbasis(dmatrix::Array{Float64,3}, GP::GraphPart; cfspec::Float64 = 1.0, flatten::Any = 1.0) # determine the cost functional to be used costfun = cost_functional(cfspec) # constants and dmatrix cleanup fcols = Base.size(dmatrix,3) dmatrix[ abs.(dmatrix) .< 10^2 * eps() ] .= 0 dmatrix0 = deepcopy(dmatrix) # keep the original dmatrix as dmatrix0 # "flatten" dmatrix if fcols > 1 if !isnothing(flatten) dmatrix = dmatrix_flatten(dmatrix, flatten)[:,:,1] end end dmatrix = dmatrix.^cfspec # Initialization. Store the expanding coeffcients from matrix into a list of dictionary (inbuilt hashmap in Julia) # The entry `coeffdict[j][(k,l)]` corresponds to the coefficient of basis-vector on level j with region k and tag l. tag = convert(Array{Int,2},GP.tag) tag_r = rs_to_region(GP.rs, GP.tag) (m,n) = size(dmatrix) coeffdict = Array{Dict{Tuple{Int,Int},Float64}}(undef, n) for i = 1:n coeffdict[i]= Dict{Tuple{Int,Int},Float64}((tag_r[j,i],tag[j,i]) => dmatrix[j,i] for j=1:m) end # TAG_tf stores the time-or-frequency information on every iteration # COEFFDICT stores the corresponding cost-functional values. COEFFDICT = Vector(undef, n) TAG_tf = Vector(undef, n) # Initialization of the first iteration COEFFDICT[1] = coeffdict TAG_tf_init = Array{Dict{Tuple{Int,Int},Bool}}(undef, n) for j = 1:n TAG_tf_init[j] = Dict(key => true for key in keys(coeffdict[j])) end TAG_tf[1] = TAG_tf_init # Iterate forward. For each entry in `COEFFDICT[i+1]`, we compare two (or one) entries in 'COEFFDICT[i]' on time-direction and two (or one) on frequency-direction. # Those two groups reprensent the same subspace. We compare the cost-functional value of them and choose the smaller one as a new entry in 'COEFFDICT[i+1]' # 'TAG_tf[i+1]' records if frequency-direction (1) or time-direction (0) was chosen. for i = 1:(n-1) COEFFDICT[i+1], TAG_tf[i+1] = tf_core_new(COEFFDICT[i]) end # Iterate backward with the existing tag_tf information to recover the best-basis. bestbasis_tag = TAG_tf[n] for i = (n-1):-1:1 bestbasis_tag = tf_basisrecover_new(TAG_tf[i],bestbasis_tag) end # Change the data structure from dictionary to matrix #bestbasis = zeros(m,n) #bestbasis_tag_matrix = zeros(Int,m,n) levlist = Vector{Tuple{Int,Int}}(undef, 0) dvec = Vector{Float64}(undef, 0) for j = 1:n for i = 1:m k = tag_r[i,j] l = tag[i,j] if haskey(bestbasis_tag[j],(k,l)) #bestbasis_tag_matrix[i,j] = 1 push!(levlist, (i,j)) #bestbasis[i,j] = dmatrix[i,j] push!(dvec, dmatrix[i,j]) end end end BS = BasisSpec(levlist, c2f = true, description = "eGHWT Best Basis") dvec = dmatrix2dvec(dmatrix0, GP, BS) return dvec, BS end # of function ghwt_tf_bestbasis const eghwt_bestbasis = ghwt_tf_bestbasis # This should be a useful alias! end # of module GHWT_tf_1d
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
24892
module GHWT_tf_2d include("utils.jl") using ..GraphSignal, ..GraphPartition, ..BasisSpecification, ..GHWT, ..GHWT_2d, LinearAlgebra include("common.jl") include("partition_fiedler.jl") export ghwt_tf_init_2d, ghwt_tf_bestbasis_2d, ghwt_tf_synthesis_2d, ghwt_tf_init_2d_Lindberg, eghwt_init_2d, eghwt_bestbasis_2d, eghwt_synthesis_2d, eghwt_init_2d_Lindberg, BS2loc """ tf2d_init(tag::Matrix{Int},tag_r::Matrix{Int}) Storing the relation between the coefficient location in the 2D coefficients matrix of all levels with the (level, tag, region) information ### Input Arguments * `tag`: The matrix of the tag information * `tag_r`: The matrix of the region information ### Output Arguments * `tag2ind`: tag2ind[(j,k,l)] is the location of the column of coefficients on level j, region k and tag l * `ind2tag`: key and item of dicionary `tag2ind` interchanged Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function tf2d_init(tag::Matrix{Int},tag_r::Matrix{Int}) (m,n) = size(tag) tag2ind = Dict{Tuple{Int,Int,Int},Int}() ind2tag = Dict{Int,Tuple{Int,Int,Int}}() for j = 1:n for i = 1:m tag2ind[(j,tag_r[i,j],tag[i,j])] = i + (j-1)*m ind2tag[i+(j-1)*m] = (j,tag_r[i,j],tag[i,j]) end end return tag2ind, ind2tag end """ dmatrix_new,tag2ind_new,ind2tag_new,tag_tf = tf_core_2d_col(dmatrix::Matrix{Float64},tag2ind::Dict{Tuple{Int,Int,Int},Int},ind2tag::Dict{Int,Tuple{Int,Int,Int}},jmax::Integer) One forward iteration of 2-d time-frequency adapted ghwt on the column direction ### Input Arguments * `dmatrix`: The cost-functional values of coeffcients * `tag2ind`: tag2ind[(j,k,l)] is the location of the column of coefficients on level j, region k and tag l * `ind2tag`: key and item of dicionary `tag2ind` interchanged ### Output Arguments * `dmatrix_new`: The cost-functional values of coeffcients * `tag2ind_new`: tag2ind_new[(j,k,l)] is the location of the column of coefficients on level j, region k and tag l * `ind2tag_new`: key and item of dicionary `tag2ind` interchanged * `tag_tf`: recording the time-or-frequency information Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function tf_core_2d_col(dmatrix::Matrix{Float64},tag2ind::Dict{Tuple{Int,Int,Int},Int},ind2tag::Dict{Int,Tuple{Int,Int,Int}},jmax::Integer) # power of the cost-functional costp = 1 p,q = size(dmatrix) dmatrix_new = zeros(p,q) # Initialization tag_tf = zeros(Bool,(p,q)) tag2ind_new = Dict{Tuple{Int,Int,Int},Int}() ind2tag_new = Dict{Int,Tuple{Int,Int,Int}}() s = 1 # Iterate through columns for i = 1:q # Find out the corresponding level,region,tag information j,k,l = ind2tag[i] # only look at the entry with even tag l to avoid duplication if l%2 == 0 && j < jmax # search for the (j,k,l+1) entry. # the (j,k,l) and (j,k,l+1) span the same subspace as (j+1,2*k,l/2) and (j+1,2*k+1,l/2) # (j,k,l) and (j,k,l+1) are `frequency-direction` # (j,k,l) and (j,k,l+1) are `time-direction` if haskey(tag2ind,(j,k,l+1)) # check for degenerate case ((j,k,l+1) doesn't exist) freqcos = abs.(dmatrix[:,i]).^costp + abs.(dmatrix[:,tag2ind[(j,k,l+1)]]).^costp else freqcos = abs.(dmatrix[:,i]).^costp end if ~haskey(tag2ind,(j+1,2*k,l/2)) # check for degenerate case ((j+1,2*k,l/2) or (j+1,2*k+1,l/2) doesn't exist) timecos = abs.(dmatrix[:,tag2ind[(j+1,2*k+1,l/2)]]).^costp elseif ~haskey(tag2ind,(j+1,2*k+1,l/2)) timecos = abs.(dmatrix[:,tag2ind[(j+1,2*k,l/2)]]).^costp else timecos = abs.(dmatrix[:,tag2ind[(j+1,2*k+1,l/2)]]).^costp + abs.(dmatrix[:,tag2ind[(j+1,2*k,l/2)]]).^costp end tag_tf[:,s] = timecos.>=freqcos dmatrix_new[:,s] = tag_tf[:,s].*freqcos + .~tag_tf[:,s].*timecos ind2tag_new[s] = (j,k,l/2) tag2ind_new[(j,k,l/2)] = s s = s + 1 end end dmatrix_new = dmatrix_new[:,1:s-1] tag_tf = tag_tf[:,1:s-1] return dmatrix_new,tag2ind_new,ind2tag_new,Matrix{UInt8}(tag_tf) end """ dmatrix_new,tag2ind_new,ind2tag_new,tag_tf = tf_core_2d_row(dmatrix::Matrix{Float64},tag2ind::Dict{Tuple{Int,Int,Int},Int},ind2tag::Dict{Int,Tuple{Int,Int,Int}},jmax::Integer) Almost the same as tf_core_2d_col. But all the operations on matrix are row-wise. Due to the column-based matrix feature of Julia language. We are currently only using the tf_core_2d_col here. ### Input Arguments * `dmatrix`: The cost-functional values of coeffcients * `tag2ind`: tag2ind[(j,k,l)] is the location of the column of coefficients on level j, region k and tag l * `ind2tag`: key and item of dicionary `tag2ind` interchanged ### Output Arguments * `dmatrix_new`: The cost-functional values of coeffcients * `tag2ind_new`: tag2ind_new[(j,k,l)] is the location of the row of coefficients on level j, region k and tag l * `ind2tag_new`: key and item of dicionary `tag2ind` interchanged * `tag_tf`: recording the time-or-frequency information Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function tf_core_2d_row(dmatrix::Matrix{Float64},tag2ind::Dict{Tuple{Int,Int,Int},Int},ind2tag::Dict{Int,Tuple{Int,Int,Int}},jmax::Integer) costp = 1 p,q = size(dmatrix) dmatrix_new = zeros(p,q) tag_tf = zeros(Bool,(p,q)) tag2ind_new = Dict{Tuple{Int,Int,Int},Int}() ind2tag_new = Dict{Int,Tuple{Int,Int,Int}}() s = 1 for i = 1:p j,k,l = ind2tag[i] if l%2 == 0 && j < jmax if haskey(tag2ind,(j,k,l+1)) freqcos = abs.(dmatrix[i,:]).^costp + abs.(dmatrix[tag2ind[(j,k,l+1)],:]).^costp else freqcos = abs.(dmatrix[i,:]).^costp end if ~haskey(tag2ind,(j+1,2*k,l/2)) timecos = abs.(dmatrix[tag2ind[(j+1,2*k+1,l/2)],:]).^costp elseif ~haskey(tag2ind,(j+1,2*k+1,l/2)) timecos = abs.(dmatrix[tag2ind[(j+1,2*k,l/2)],:]).^costp else timecos = abs.(dmatrix[tag2ind[(j+1,2*k+1,l/2)],:]).^costp + abs.(dmatrix[tag2ind[(j+1,2*k,l/2)],:]).^costp end tag_tf[s,:] = timecos.>=freqcos dmatrix_new[s,:] = tag_tf[s,:].*freqcos + .~tag_tf[s,:].*timecos ind2tag_new[s] = (j,k,l/2) tag2ind_new[(j,k,l/2)] = s s = s + 1 end end dmatrix_new = dmatrix_new[1:s-1,:] tag_tf = tag_tf[1:s-1,:] return dmatrix_new,tag2ind_new,ind2tag_new,Matrix{UInt8}(tag_tf) end """ Bbasis, infovec = ghwt_tf_bestbasis_2d(dmatrix::Matrix{Float64},GProws::GraphPart,GPcols::GraphPart) Implementation of 2d time-frequency adapted GHWT method. Modified from the idea in paper "Image compression with adaptive Haar-Walsh tilings" by Maj Lindberg and Lars F. Villemoes. ### Input Arguments * `dmatrix`: The ghwt expanding coefficients of matrix on all levels contatenated in a 2d matrix. * `GProws`: Corresponding to the affinity matrix on rows. * `GPcols`: Corresponding to the affinity matrix on cols. ### Output Arguments * `Bbasis`: The coefficients of the best-basis. * `infovec`: [infovec[i,1],infovec[i,2]] is the location of Bbasis[i] in dmatrix. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_tf_bestbasis_2d(matrix::Matrix{Float64},GProws::GraphPart,GPcols::GraphPart) dmatrix = ghwt_analysis_2d(matrix, GProws, GPcols) # Initialization tag_r_row = rs_to_region(GProws.rs, GProws.tag) tag_r_col = rs_to_region(GPcols.rs, GPcols.tag) tag2ind_row,ind2tag_row = tf2d_init(Matrix{Int}(GProws.tag),Matrix{Int}(tag_r_row)) tag2ind_col,ind2tag_col = tf2d_init(Matrix{Int}(GPcols.tag),Matrix{Int}(tag_r_col)) jmax_col = size(GPcols.tag,2) jmax_row = size(GProws.tag,2) # (level,region,tag) information on the columns TAG2IND_col = Vector(undef, jmax_col) TAG2IND_col[1] = tag2ind_col IND2TAG_col = Vector(undef, jmax_col) IND2TAG_col[1] = ind2tag_col # (level,region,tag) information on the rows TAG2IND_row = Vector(undef, jmax_row) TAG2IND_row[1] = tag2ind_row IND2TAG_row = Vector(undef, jmax_row) IND2TAG_row[1] = ind2tag_row # recording if time or frequency direction is chosen TAG_tf = Matrix(undef, jmax_row,jmax_col) # storing the cost functional values DMATRIX = Matrix(undef, jmax_row, jmax_col) DMATRIX[1,1] = dmatrix # comparison in the row direction for i=1:(jmax_row - 1) DMATRIX[i+1,1], TAG2IND_row[i+1], IND2TAG_row[i+1], TAG_tf[i+1,1] = tf_core_2d_col(Array{Float64,2}(DMATRIX[i,1]'), TAG2IND_row[i], IND2TAG_row[i],jmax_row+1-i) TAG_tf[i+1,1] = Array{UInt8,2}((TAG_tf[i+1,1] .+ UInt8(2))') DMATRIX[i+1,1] = Array{Float64,2}(DMATRIX[i+1,1]') end # comparison in the column direction for i=1:(jmax_col - 1) DMATRIX[1,i+1], TAG2IND_col[i+1], IND2TAG_col[i+1], TAG_tf[1,i+1] = tf_core_2d_col(DMATRIX[1,i],TAG2IND_col[i], IND2TAG_col[i], jmax_col+1-i) end #DMATRIX[1,1] = 0 # release the memory # comparison in both directions for i = 2:jmax_row for j = 2:jmax_col (temp_col,_,_,temp_tf_col) = tf_core_2d_col(DMATRIX[i,j-1], TAG2IND_col[j-1], IND2TAG_col[j-1],jmax_col + 2 - j) (temp_row,_,_,temp_tf_row) = tf_core_2d_col(Array{Float64,2}(DMATRIX[i-1,j]'), TAG2IND_row[i-1], IND2TAG_row[i-1],jmax_row + 2 - i) temp_row = Array{Float64,2}(temp_row') temp_tf_row = Array{UInt8,2}((temp_tf_row .+ UInt8(2))') row_or_col = temp_col.<=temp_row DMATRIX[i,j] = row_or_col.*temp_col + .~row_or_col.*temp_row TAG_tf[i,j] = Matrix{UInt8}(row_or_col).*temp_tf_col + Matrix{UInt8}(.~row_or_col).*temp_tf_row #DMATRIX[i-1,j] = 0 end #DMATRIX[i,1] = 0 # release the memory end #for j = 2: jmax_col #DMATRIX[jmax_row, j] = 0 # release the memory #end #recover the bestbasis infovec = Array{Int}([jmax_row; jmax_col; 1; 1]) for iter = 1:(jmax_row + jmax_col - 2) newinfovec = -1*ones(Int,(4,2*size(infovec,2))) for h = 1:size(infovec,2) m = infovec[1,h] n = infovec[2,h] p = infovec[3,h] q = infovec[4,h] #if the bestbasis comes from column direction if TAG_tf[m,n][p,q] == 0 #time domain j,k,l = IND2TAG_col[n][q] if haskey(TAG2IND_col[n-1],(j+1,2*k,l)) q1 = TAG2IND_col[n-1][(j+1,2*k,l)] newinfovec[:,2*h-1] = [m;n-1;p;q1] end if haskey(TAG2IND_col[n-1],(j+1,2*k+1,l)) q2 = TAG2IND_col[n-1][(j+1,2*k+1,l)] newinfovec[:,2*h] = [m;n-1;p;q2] end end if TAG_tf[m,n][p,q] == 1 # frequency domain j,k,l = IND2TAG_col[n][q] if haskey(TAG2IND_col[n-1],(j,k,2*l)) q1 = TAG2IND_col[n-1][(j,k,2*l)] newinfovec[:,2*h-1] = [m;n-1;p;q1] end if haskey(TAG2IND_col[n-1],(j,k,2*l+1)) q2 = TAG2IND_col[n-1][(j,k,2*l+1)] newinfovec[:,2*h] = [m;n-1;p;q2] end end #if the bestbasis comes from row direction if TAG_tf[m,n][p,q] == 2 # time domain j,k,l = IND2TAG_row[m][p] if haskey(TAG2IND_row[m-1],(j+1,2*k,l)) p1 = TAG2IND_row[m-1][(j+1,2*k,l)] newinfovec[:,2*h-1] = [m-1;n;p1;q] end if haskey(TAG2IND_row[m-1],(j+1,2*k+1,l)) p2 = TAG2IND_row[m-1][(j+1,2*k+1,l)] newinfovec[:,2*h] = [m-1;n;p2;q] end end if TAG_tf[m,n][p,q] == 3 # frequency domain j,k,l = IND2TAG_row[m][p] if haskey(TAG2IND_row[m-1],(j,k,2*l)) p1 = TAG2IND_row[m-1][(j,k,2*l)] newinfovec[:,2*h-1] = [m-1;n;p1;q] end if haskey(TAG2IND_row[m-1],(j,k,2*l+1)) p2 = TAG2IND_row[m-1][(j,k,2*l+1)] newinfovec[:,2*h] = [m-1;n;p2;q] end end end infovec = newinfovec[:,newinfovec[1,:].!=-1] end #return Array{Float64,2}(dmatrix[sub2ind(size(dmatrix),infovec[3,:],infovec[4,:])]'),infovec[3:4,:] return dmatrix[(LinearIndices(size(dmatrix)))[CartesianIndex.(infovec[3,:],infovec[4,:])]],infovec[3:4,:] end """ ghwt_tf_synthesis_2d_core!(dmatrix::Array{Float64,3},tag::Array{Int,2},rs::Array{Int,2}) Core function of ghwt_tf_synthesis_2d. Synthesize on column direction ### Input Arguments * `dmatrix`: Same size as dmatrix, but only selected basis vectors are nonzero with expanding coeffcients. * `tag`: Tag information in GP. * `rs`: Rs information in GP. ### Output Arguments * `dmatrix`: Synthesized on column direction. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_tf_synthesis_2d_core!(dmatrix::Array{Float64,3},tag::Array{Int,2},rs::Array{Int,2}) jmax = size(tag,2) for j = 1:jmax-1 regioncount = count(!iszero, rs[:,j]) - 1 for r = 1:regioncount # the index that marks the start of the first subregion rs1 = rs[r,j] # the index that is one after the end of the second subregion rs3 = rs[r+1,j] #the number of points in the current region n = rs3 - rs1 # proceed if not all coefficients are zero in this region if count(!iszero, dmatrix[rs1:rs3-1,j,:]) > 0 if n == 1 ### SCALING COEFFICIENT (n == 1) dmatrix[rs1,j+1,:] = dmatrix[rs1,j,:] + dmatrix[rs1,j+1,:] elseif n > 1 # the index that marks the start of the second subregion rs2 = rs1+1; while rs2 < rs3 && tag[rs2,j+1] != 0 rs2 = rs2+1; end # the parent region is a copy of the subregion if rs2 == rs3 dmatrix[rs1:rs3-1,j+1,:] = dmatrix[rs1:rs3-1,j,:] + dmatrix[rs1:rs3-1,j+1,:] # the parent region has 2 child regions else # the number of points in the first subregion n1 = rs2 - rs1 # the number of points in the second subregion n2 = rs3 - rs2 ### SCALING COEFFICIENTS dmatrix[rs1,j+1,:] = ( sqrt(n1).*dmatrix[rs1,j,:] + sqrt(n2).*dmatrix[rs1+1,j,:] )./sqrt(n) + dmatrix[rs1,j+1,:] dmatrix[rs2,j+1,:] = ( sqrt(n2).*dmatrix[rs1,j,:] - sqrt(n1).*dmatrix[rs1+1,j,:] )./sqrt(n) + dmatrix[rs2,j+1,:] # HAAR-LIKE & WALSH-LIKE COEFFICIENTS # search through the remaining coefficients in each subregion parent = rs1+2 child1 = rs1+1 child2 = rs2+1 while child1 < rs2 || child2 < rs3 # subregion 1 has the smaller tag if child2 == rs3 || (tag[child1,j+1] < tag[child2,j+1] && child1 < rs2) dmatrix[child1,j+1,:] = dmatrix[parent,j,:] + dmatrix[child1,j+1,:] child1 = child1+1; parent = parent+1; # subregion 2 has the smaller tag elseif child1 == rs2 || (tag[child2,j+1] < tag[child1,j+1] && child2 < rs3) dmatrix[child2,j+1,:] = dmatrix[parent,j,:] + dmatrix[child2,j+1,:] child2 = child2+1; parent = parent+1; # both subregions have the same tag else dmatrix[child1,j+1,:] = ( dmatrix[parent,j,:] + dmatrix[parent+1,j,:] )/sqrt(2) + dmatrix[child1,j+1,:] dmatrix[child2,j+1,:] = ( dmatrix[parent,j,:] - dmatrix[parent+1,j,:] )/sqrt(2) + dmatrix[child2,j+1,:] child1 = child1+1; child2 = child2+1; parent = parent+2; end end end end end end end end """ matrix = ghwt_tf_synthesis_2d(dmatrix::Matrix{Float64}, GProws::GraphPart, GPcols::GraphPart) Synthesis the matrix from the coefficients of selected basis vectors. ### Input Arguments * `dmatrix`: Only selected basis vectors are nonzero with expanding coeffcients. * `GProws`: Corresponding to the affinity matrix on rows. * `GPcols`: Corresponding to the affinity matrix on cols. ### Output Arguments * `matrix`: Synthesized matrix Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function ghwt_tf_synthesis_2d(dvec::Vector{Float64}, infovec::Matrix{Int}, GProws::GraphPart, GPcols::GraphPart) tag_col, rs_col = GPcols.tag, GPcols.rs tag_row, rs_row = GProws.tag, GProws.rs fcols, jmax_col = size(tag_col); frows, jmax_row = size(tag_row); dmatrix = zeros(frows*jmax_row, fcols*jmax_col) for i in 1:size(infovec,2) dmatrix[infovec[1,i],infovec[2,i]] = dvec[i] end matrix_r = Array{Float64,2}(dmatrix'); matrix_r = reshape(matrix_r, fcols, jmax_col, frows*jmax_row); ghwt_tf_synthesis_2d_core!(matrix_r, Matrix{Int}(tag_col), Matrix{Int}(rs_col)); matrix_r = matrix_r[:,end,:]; #matrix_r = reshape(matrix_r, fcols, frows*jmax_row); matrix_r = reshape(Array{Float64,2}(matrix_r'),frows,jmax_row, fcols); ghwt_tf_synthesis_2d_core!(matrix_r, Matrix{Int}(tag_row), Matrix{Int}(rs_row)); matrix_r = matrix_r[:,end,:]; #matrix_r = reshape(matrix_r,frows, fcols); matrix = zeros(frows, fcols) matrix[GProws.ind,GPcols.ind] = matrix_r return matrix end """ dmatrix, GProws, GPcols = ghwt_tf_init_2d(matrix::Matrix{Float64}) Partition matrix first to get GProws and GPcols. Then expand matrix in two directions to get dmatrix ### Input Arguments * `matrix::Matrix{Float64}`: an input matrix ### Output Argument * `GProws::GraphPart`: partitioning using rows as samples * `GPcols::GraphPart`: partitioning using cols as samples * `dmatrix::matrix{Float64}`: expansion coefficients of matrix """ function ghwt_tf_init_2d(matrix::Matrix{Float64}) #Partition matrix recuisively using Dhillon's method GProws, GPcols = PartitionTreeMatrixDhillon(matrix) ghwt_core!(GProws) ghwt_core!(GPcols) matrix_re = matrix[GProws.ind, GPcols.ind] (N, jmax_row) = size(GProws.rs) N = N-1 # expand on the row direction (frows, fcols) = size(matrix_re) dmatrix = zeros((N,jmax_row,fcols)) dmatrix[:,jmax_row,:] = matrix_re ghwt_core!(GProws, dmatrix) dmatrix = reshape(dmatrix, (frows*jmax_row, fcols))' # expand on the column direction (N, jmax_col) = size(GPcols.rs) N = N - 1 dmatrix2 = zeros(N,jmax_col,size(dmatrix,2)) dmatrix2[:, jmax_col, :] = dmatrix ghwt_core!(GPcols, dmatrix2) dmatrix = reshape(dmatrix2, (fcols*jmax_col, frows*jmax_row))' return Array{Float64,2}(dmatrix), GProws, GPcols end function ghwt_tf_init_2d_Lindberg(matrix::Matrix{Float64}) #Partition matrix recuisively using Dhillon's method m,n = size(matrix) GProws = regularhaar(m) GPcols = regularhaar(n) ghwt_core!(GProws) ghwt_core!(GPcols) matrix_re = matrix[GProws.ind, GPcols.ind] (N, jmax_row) = size(GProws.rs) N = N-1 # expand on the row direction (frows, fcols) = size(matrix_re) dmatrix = zeros((N,jmax_row,fcols)) dmatrix[:,jmax_row,:] = matrix_re ghwt_core!(GProws, dmatrix) dmatrix = reshape(dmatrix, (frows*jmax_row, fcols))' # expand on the column direction (N, jmax_col) = size(GPcols.rs) N = N - 1 dmatrix2 = zeros(N,jmax_col,size(dmatrix,2)) dmatrix2[:, jmax_col, :] = dmatrix ghwt_core!(GPcols, dmatrix2) dmatrix = Array{Float64,2}(reshape(dmatrix2, (fcols*jmax_col, frows*jmax_row))') return dmatrix, GProws, GPcols end function regularhaar(n::Int) if log2(n)%1 != 0 error("Input number should be some power of 2") else ind = Array{Int64}(1:n) l = Int64(log2(n)) rs = zeros(Int64,n+1,l+1) for j = 1:l+1 gap = Int64(n/(2^(j-1))) for i = 1:(2^(j-1) + 1) rs[i,j] = Int64((i-1)*gap + 1) end end end return GraphPart(ind, rs) end """ dmatrix = ghwt_tf_init_2d(matrix::Matrix{Float64}, GProws::GraphPart, GPcols::GraphPart) Partition matrix first to get GProws and GPcols. Then expand matrix in two directions to get dmatrix ### Input Arguments * `matrix::Matrix{Float64}`: an input matrix * `GProws::GraphPart`: partitioning using rows as samples * `GPcols::GraphPart`: partitioning using cols as samples ### Output Argument * `dmatrix::matrix{Float64}`: expansion coefficients of matrix """ function ghwt_tf_init_2d(matrix::Matrix{Float64}, GProws::GraphPart, GPcols::GraphPart) ghwt_core!(GProws) ghwt_core!(GPcols) matrix_re = matrix[GProws.ind, GPcols.ind] (N, jmax_row) = size(GProws.rs) N = N-1 # expand on the row direction (frows, fcols) = size(matrix_re) dmatrix = zeros((N,jmax_row,fcols)) dmatrix[:,jmax_row,:] = matrix_re ghwt_core!(GProws, dmatrix) dmatrix = reshape(dmatrix, (frows*jmax_row, fcols))' # expand on the column direction (N, jmax_col) = size(GPcols.rs) N = N - 1 dmatrix2 = zeros(N,jmax_col,size(dmatrix,2)) dmatrix2[:, jmax_col, :] = dmatrix ghwt_core!(GPcols, dmatrix2) dmatrix = Array{Float64,2}(reshape(dmatrix2, (fcols*jmax_col, frows*jmax_row))') return dmatrix end function BS2ind(GP::GraphPart, BS::BasisSpec) tag = GP.tag N = size(tag,1) jmax = size(tag,2) tag_r = rs_to_region(GP.rs, tag) tag2ind, ind2tag = tf2d_init(Array{Int,2}(tag),tag_r) ind = fill(0, N) if BS.c2f for i = 1:N j2, j = BS.levlist[i] k = tag_r[j2,j] l = tag[j2,j] ind[i] = tag2ind[(j,k,l)] end else tag_r_f2c = Array{Int,2}(fine2coarse!(GP, dmatrix = Array{Float64,3}(reshape(tag_r,(size(tag_r,1),size(tag_r,2),1))), coefp = true)[:,:,1]) tag_f2c = GP.tagf2c for i = 1:N j2, j = BS.levlist[i] k = tag_r_f2c[j2,j] l = tag_f2c[j2,j] ind[i] = tag2ind[(jmax + 1 - j, k, l)] end end return ind end function BS2loc(dmatrix::Matrix{Float64}, GProws::GraphPart, GPcols::GraphPart, BSrows::BasisSpec, BScols::BasisSpec) indrows = BS2ind(GProws, BSrows) indcols = BS2ind(GPcols, BScols) m = length(indrows) n = length(indcols) loc = fill(0, (2,m*n)) dvec = fill(0., m*n) global idx = 1 for i = 1:n for j = 1:m loc[1,idx] = indrows[j] loc[2,idx] = indcols[i] dvec[idx] = dmatrix[indrows[j], indcols[i]] global idx += 1 end end return dvec, loc end # A useful and meaningful set of aliases here const eghwt_init_2d = ghwt_tf_init_2d const eghwt_bestbasis_2d = ghwt_tf_bestbasis_2d const eghwt_synthesis_2d = ghwt_tf_synthesis_2d const eghwt_init_2d_Lindberg = ghwt_tf_init_2d_Lindberg end # of module GHWT_tf_2d
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
17988
module GraphPartition using ..GraphSignal, SparseArrays, LinearAlgebra include("partition_fiedler.jl") include("utils.jl") export GraphPart, partition_tree_fiedler, partition_tree_matrixDhillon # GraphPart data structure and constructors """ GP = GraphPart(ind::Vector{Int}, rs::Matrix{Int}, tag::Matrix{Int}, compinfo::Matrix{Int}, rsf2c::Matrix{Int}, tagf2c::Matrix{Int}, compinfof2c::Matrix{Int}, inds::Matrix{Int}, method::Vector{Symbol}) is a data structure for a GraphPart object containing the following fields: * `ind::Vector{Int}`: ordering of the indices on the finest level * `rs::Matrix{Int}`: regionstarInt (coarse-to-fine) <==> the index in `ind` of the first point in region number `i` is `rs[i]` * `tag::Matrix{Int}`: tag info for the GHWT coarse-to-fine basis * `compinfo::Matrix{Int}`: indicates whether the coefficient was formed from 2 coefficenInt (value is nonzero) or from only 1 coefficient (value is zero); when a scaling and Haar-like coefficient are formed, their corresponding values in compinfo indicate the number of nodes in each of the 2 subregions * `rsf2c::Matrix{Int}`: the fine-to-coarse version of `rs` * `tagf2c::Matrix{Int}`: the fine-to-coarse version of `tag` * `compinfof2c::Matrix{Int}`: the fine-to-coarse version of `compinfo` * `inds::Matrix{Int}`: ordering of the indices on all levels * `method::Symbol`: how the partition tree was constructed The unsigned integer depends on the size of the underlying graph. Copyright 2015 The RegenInt of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) | Translated and modified by Naoki Saito, Feb. 7, 2017 Revised for two parameters by Naoki Saito, Feb. 24, 2017 """ mutable struct GraphPart ind::Vector{Int} # ordering of the indices on the finest level rs::Matrix{Int} # `rs[i,j]` = the index in `ind` of the first # point in Region `i` at level j tag::Matrix{Int} # Int <: Int because max(tag) <= log2(max(T)) compinfo::Matrix{Int} # coef was from 2 coefs or from 1 coef rsf2c::Matrix{Int} # f2c version of `rs` tagf2c::Matrix{Int} # f2c version of `tag` compinfof2c::Matrix{Int} # f2c version of `compinfo` inds::Matrix{Int} # ordering of the indices on all levels method::Symbol # specification of graph partition method # An inner constructor here. function GraphPart(ind::Vector{Int}, rs::Matrix{Int}; tag::Matrix{Int} = Matrix{Int}(undef, 0, 0), compinfo::Matrix{Int} = Matrix{Int}(undef, 0, 0), rsf2c::Matrix{Int} = Matrix{Int}(undef, 0, 0), tagf2c::Matrix{Int} = Matrix{Int}(undef, 0, 0), compinfof2c::Matrix{Int} = Matrix{Int}(undef, 0, 0), inds::Matrix{Int} = Matrix{Int}(undef, 0, 0), method::Symbol = :unspecified) # Sanity checks if Base.size(rs, 1) != Base.length(ind) + 1 @warn("size(rs,1) must be length(ind) + 1") @warn("both rs and ind now become null arrays!") ind = Vector{Int}(undef, 0) rs = Matrix{Int}(undef, 0, 0) end if Base.length(tag) != 0 && (Base.size(rs, 1) != Base.size(tag, 1) + 1 || Base.size(rs, 2) != Base.size(tag, 2)) @warn("tag size is inconsistent with rs size.") @warn("tag now becomes a null array!") tag = Matrix{Int}(undef, 0, 0) end if Base.length(compinfo) != 0 && ( Base.size(rs, 1) != Base.size(compinfo, 1) + 1 || Base.size(rs, 2) != Base.size(compinfo, 2) ) @warn("compinfo size is inconsistent with rs size.") @warn("compinfo now becomes a null array!") compinfo = Matrix{Int}(undef, 0, 0) end if Base.length(rsf2c) != 0 && Base.length(rsf2c) != Base.length(rs) @warn("length(rsf2c) must be length(rs)") @warn("rsf2c now becomes a null array!") rsf2c = Matrix{Int}(undef, 0, 0) end if Base.length(tagf2c) != 0 && Base.length(tagf2c) != Base.length(tag) @warn("length(tagf2c) must be length(tag)") @warn("tagf2c now becomes a null array!") tagf2c = Matrix{Int}(undef, 0, 0) end if Base.length(compinfof2c) != 0 && Base.length(compinfof2c) != Base.length(compinfo) @warn("length(compinfof2c) must be length(compinfo)") @warn("compf2c now becomes a null array!") compf2c = Matrix{Int}(undef, 0, 0) end new(ind, rs, tag, compinfo, rsf2c, tagf2c, compinfof2c, inds, method) end # of an inner constructor GraphPart end # of type GraphPart """ GP = partition_tree_fiedler(G::GraphSig; method::Symbol = :Lrw, swapRegion::Bool = true) Generate a partition tree for a graph using the Fiedler vector of either L (the unnormalized Laplacian) or L_rw (the random-walk normalized Laplacian). ### Input ArgumenInt * `G::GraphSig`: an input GraphSig object * `method::Symbol`: how the partition tree was constructed (default: :Lrw) * `swapRegion::Bool`: swap the child regions based on the sum of the subgraphs' edge weights (default: true) ### Output Argument * `GP::GraphPart`: an ouput GraphPart object Copyright 2015 The RegenInt of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) | Translated and modified by Naoki Saito, Feb. 7, 2017 """ function partition_tree_fiedler(G::GraphSignal.GraphSig; method::Symbol = :Lrw, swapRegion::Bool = true) # # 0. Preliminary stuff # # constanInt N = G.length jmax = max(3 * floor(Int, log2(N)), 4) # jmax >= 4 is guaranteed. # This jmax is the upper bound of the true jmax; the true jmax # is computed as the number of columns of the matrix `rs` in the end. # TRACKING VARIABLES # `ind` records the way in which the nodes are indexed on each level ind = Vector{Int}(1:N) # `inds` records the way in which the nodes are indexed on all levels inds = zeros(Int, N, jmax) inds[:, 1] = ind # `rs` stands for regionstarInt, meaning that the index in `ind` of the first # point in region number `i` is `rs[i]` rs = zeros(Int, N + 1, jmax) rs[1, :] .= 1 rs[2, 1] = N + 1 # # 1. Partition the graph to yield rs, ind, and jmax # j = 1 # j=1 in julia <=> j=0 in theory regioncount = 0 rs0 = 0 # define here for the whole loops, # which differs from MAIntAB. while regioncount < N #regioncount = countnz(rs[:,j]) - 1 regioncount = count(!iszero,rs[:, j]) - 1 # the number of regions on level j if j == jmax # add a column to rs and inds for level j+1, if necessary rs = hcat(rs, vcat(Int(1), zeros(Int,N))) inds = hcat(inds, zeros(Int, N)) jmax = jmax + 1 end # for tracking the child regions rr = 1 for r = 1:regioncount # cycle through the parent regions rs1 = rs[r, j] # the start of the parent region rs2 = rs[r + 1, j] # 1 node after the end of the parent region n = rs2 - rs1 # the number of nodes in the parent region if n > 1 # regions with 2 or more nodes indrs = ind[rs1:(rs2 - 1)] # partition the current region (pm, ) = partition_fiedler(G.W[indrs,indrs], method = method) # determine the number of poinInt in child region 1 n1 = sum(pm .> 0) # switch regions 1 and 2, if necessary, based on the sum of # edge weighInt to the previous child region (i.e., cousin) if r > 1 && swapRegion # MAIntAB: sum(sum(...)) instead of sum(...) if sum(G.W[ind[rs0:(rs1 - 1)], indrs[pm .> 0]]) < sum(G.W[ind[rs0:(rs1 - 1)], indrs[pm .< 0]]) pm = -pm n1 = n - n1 end end # update the indexing ind[rs1:(rs1 + n1 - 1)] = indrs[pm .> 0] ind[(rs1 + n1):(rs2 - 1)] = indrs[pm .< 0] # update the region tracking rs[rr + 1, j + 1] = rs1 + n1 rs[rr + 2, j + 1] = rs2 rr = rr + 2 rs0 = rs1 + n1 elseif n == 1 # regions with 1 node rs[rr + 1, j + 1] = rs2 rr = rr + 1 rs0 = rs1 end # of if n > 1 ... elseif n==1 construct end # of for r=1:regioncount j = j + 1 inds[:, j] = ind end # of while regioncount < N statement # # 2. Postprocessing # # get rid of excess columns in rs rs = rs[:, 1:(j - 1)] # in MAIntAB, it was rs(:,j:end) = []; # get rid of excess columns in inds inds = inds[:, 1:(j - 1)] # create a GraphPart object return GraphPart(ind, rs; inds = inds, method = method) end # of function partition_tree_fiedler """ GProws, GPcols = partition_tree_matrixDhillon(matrix::Matrix{Float64}) Recursively partition the rows and columns of the matrix using the bipartite model proposed by Dhillon in "Co-clustering documents and words using Bipartite Spectral Graph Partitioning" ### Input Arguments * `matrix::Matrix{Float64}`: an input matrix ### Output Argument * `GProws::GraphPart`: partitioning using rows as samples * `GPcols::GraphPart`: partitioning using cols as samples """ function partition_tree_matrixDhillon(matrix::Matrix{Float64}) ## 0. Preliminary stuff # constants (rows, cols) = size(matrix) N = max(rows,cols) jmax = Int(max(3*floor(log2(N)),4)) ### Tracking variables for the rows # order index ind_rows = Vector{Int}(1:rows) ind_cols = Vector{Int}(1:cols) # regionstarts rs_rows = zeros(Int, (N+1,jmax)) rs_rows[1,:] .= 1 rs_rows[2,1] = rows + 1 rs_cols = zeros(Int, (N+1,jmax)) rs_cols[1,:] .= 1 rs_cols[2,1] = cols + 1 ## 1. Partition the graph to yield rs, ind, and jmax j = 1 regioncount_rows = 0 regioncount_cols = 0 while (regioncount_rows) < rows || (regioncount_cols < cols) # the number of true regions (i.e, has 1 or more nodes) on level j regioncount_rows = length(unique(vcat(rs_rows[:,j],[0]))) - 2 regioncount_cols = length(unique(vcat(rs_cols[:,j],[0]))) - 2 # the number of total regions (including those with no nodes) false_regioncount = max(count(!iszero, rs_rows[:,j]),count(!iszero, rs_cols[:,j])) - 1 # add a column for level j+1, if necessary if j == jmax rs_rows = hcat(rs_rows,zeros(N+1)) rs_cols = hcat(rs_cols,zeros(N+1)) rs_rows[1,j+1] = 1 rs_cols[1,j+1] = 1 jmax = jmax + 1 end # for tracking the child regions (for both rows and columns) rr = 1 # cycle through the parent regions for r = 1 : false_regioncount # the start of the parent region and 1 node after the end of the parent region rs1_rows = rs_rows[r,j] rs2_rows = rs_rows[r+1,j] rs1_cols = rs_cols[r,j] rs2_cols = rs_cols[r+1,j] # the number of nodes in the parent region n_rows = rs2_rows - rs1_rows n_cols = rs2_cols - rs1_cols if (n_rows <=1) && (n_cols > 1) indrs_rows = ind_rows[rs1_rows] indrs_cols = ind_cols[rs1_cols:(rs2_cols-1)] # compute the left and right singular vectors #(u_rows, v_cols) = second_largest_singular_vectors(reshape(matrix[indrs_rows,indrs_cols],(n_rows,n_cols))) # partition the current region pm_cols = partition_vector(matrix[indrs_rows,indrs_cols]) # determine the number of points in child region 1 n1_cols = sum(pm_cols .>0) # update the column indexing ind_cols[rs1_cols:(rs1_cols+n1_cols-1)] = indrs_cols[pm_cols.>0] ind_cols[(rs1_cols+n1_cols):(rs2_cols-1)] = indrs_cols[pm_cols.<0] # update the row region tracking rs_rows[rr+1,j+1] = rs1_rows rs_rows[rr+2,j+1] = rs2_rows # update the column region tracking rs_cols[rr+1, j+1] = rs1_cols + n1_cols rs_cols[rr+2, j+1] = rs2_cols rr = rr + 2 elseif (n_rows > 1) && (n_cols <= 1) indrs_rows = ind_rows[rs1_rows:(rs2_rows-1)] indrs_cols = ind_cols[rs1_cols] # compute the left and right singular vectors #(u_rows, u_cols) = second_largest_singular_vectors(reshape(matrix[indrs_rows, indrs_cols],(n_rows,n_cols))) # partition the current region pm_rows = partition_vector(matrix[indrs_rows, indrs_cols]) # determine the number of points in child region 1 n1_rows = sum(pm_rows.>0) # update the row indexing ind_rows[rs1_rows:(rs1_rows+n1_rows-1)] = indrs_rows[pm_rows.>0] ind_rows[(rs1_rows+n1_rows):(rs2_rows-1)] = indrs_rows[pm_rows.<0] # update the row region tracking rs_rows[rr+1,j+1] = rs1_rows + n1_rows rs_rows[rr+2,j+1] = rs2_rows # update the column region tracking rs_cols[rr+1,j+1] = rs1_cols rs_cols[rr+2,j+1] = rs2_cols rr = rr + 2 elseif (n_rows > 1) && (n_cols > 1) indrs_rows = ind_rows[rs1_rows:(rs2_rows-1)] indrs_cols = ind_cols[rs1_cols:(rs2_cols-1)] # compute the left and right singular vectors (u_rows,v_cols) = second_largest_singular_vectors(matrix[indrs_rows,indrs_cols]) # partition the current region pm, = partition_fiedler_pm(vcat(u_rows, v_cols)) pm_rows = pm[1:n_rows] pm_cols = pm[(n_rows+1):end] # determine the number of points in child region 1 n1_rows = sum(pm_rows .> 0) n1_cols = sum(pm_cols .> 0) # update the row indexing ind_rows[rs1_rows:(rs1_rows + n1_rows - 1)] = indrs_rows[pm_rows .> 0] ind_rows[(rs1_rows + n1_rows):(rs2_rows - 1)] = indrs_rows[pm_rows .< 0] # update the column indexing ind_cols[rs1_cols:(rs1_cols + n1_cols - 1)] = indrs_cols[pm_cols .> 0] ind_cols[(rs1_cols + n1_cols):(rs2_cols - 1)] = indrs_cols[pm_cols .< 0] # update the row region tracking rs_rows[rr+1, j+1] = rs1_rows + n1_rows rs_rows[rr+2, j+1] = rs2_rows # update the column region tracking rs_cols[rr+1, j+1] = rs1_cols + n1_cols rs_cols[rr+2, j+1] = rs2_cols rr = rr + 2 else rs_rows[rr+1, j+1] = rs2_rows rs_cols[rr+1, j+1] = rs2_cols rr = rr + 1 end if rr > size(rs_rows,1) - 2 rs_rows = vcat(rs_rows,zeros(Int,(2,size(rs_rows,2)))) end if rr > size(rs_cols,1) - 2 rs_cols = vcat(rs_cols,zeros(Int,(2,size(rs_cols,2)))) end end j = j + 1 end # get rid of excess columns in rs_rows and rs_cols rs_rows = rs_rows[:, 1:(j-1)] rs_cols = rs_cols[:, 1:(j-1)] jmax = size(rs_rows,2) #remove duplicates M_rows = size(rs_rows,1) M_cols = size(rs_cols,1) for j = jmax:-1:1 ### ROWS # remove duplicate regionstarts unique_rows = unique(rs_rows[:,j]) if unique_rows[1] == 0 shift!(unique_rows) end rs_rows[:,j] = vcat(unique_rows, zeros(M_rows-length(unique_rows))) #remove duplicate columns of rs if (j < jmax) && (sum(rs_rows[:,j] .!= rs_rows[:,j+1]) == 0) rs_rows = rs_rows[:,setdiff(1:end,j+1)] end ### COLUMNS # remove duplicate regionscounts unique_cols = unique(rs_cols[:,j]) if unique_cols[1] == 0 shift!(unique_cols) end rs_cols[:,j] = vcat(unique_cols, zeros(M_cols-length(unique_cols))) # remove duplicate columns of rs if (j < jmax) && (sum(rs_cols[:,j].!=rs_cols[:,j+1]) == 0) rs_cols = rs_cols[:,setdiff(1:end,j+1)] end end # remove unnecessary rows and columns in the regionstarts if rows < M_rows - 1 rs_rows = rs_rows[1:(rows+1),:] end if cols < M_cols - 1 rs_cols = rs_cols[1:(cols+1),:] end # create GraphPart Objects GProws = GraphPart(ind_rows, rs_rows) GPcols = GraphPart(ind_cols, rs_cols) return GProws, GPcols # make sure the GraphPart objects meet our requirements #blablabla end function second_largest_singular_vectors(A::Matrix{Float64}) # Compute the second largest left and right singular vectors of # An = D1^(-0.5)*A*D2^(-0.5) (rows, cols) = size(A) # compute D1 and D2 and make sure there are no zeros D1 = sum(A,dims = 2) D1[D1.==0] .= max(0.01, minimum(D1[D1.>0]/10)) D2 = sum(A,dims = 1) D2[D2.==0] .= max(0.01, minimum(D2[D2.>0]/10)) # compute the singular vectors (u,D,v) = svd(Diagonal(D1[:].^(-0.5))*A*Diagonal(D2[:].^(-0.5)), full = false) if (rows > 1) && (cols > 1) # extract the second left singular vector u = u[:,2] v = v[:,2] # extract the 2nd singular vectors and multiply by D_i^(-0.5) u = D1[:].^(-0.5).*u v = D2[:].^(-0.5).*v return u, v end end function partition_vector(v:: Vector{Float64}) # Partition vector into half, diveded by the mean of the values. l = size(v[:],1) m = mean(v) pm = zeros(l) pm[v.>m] .= 1 pm[v.<=m] .= -1 if size(unique(pm),1) == 1 f = UInt(floor(l/2)) pm[1:f] .= 1 pm[f+1:end] .= -1 end return pm end end # of module GraphPartition
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
5987
using Plots """ GraphSig_Plot(G::GraphSig; symmetric::Bool = false, markersize::Float64 = 2., markercolor::Symbol = :balance, markershape::Symbol = :circle, markerstrokewidth::Float64 = 1.0, markerstrokealpha::Float64 = 1.0, markervaluevaries::Bool = true, linewidth::Float64 = 1., linecolor::Symbol = :blue, linestyle::Symbol = :solid, clim::Tuple{Float64,Float64} = (0., 0.), notitle::Bool = false, nocolorbar::Bool = false, nolegend::Bool = true, stemplot::Bool = false, sortnodes::Symbol = :normal) Display a plot of the data in a GraphSig object ### Input Argument * `G::GraphSig`: an input GraphSig object * `symmetric` symmetrize the colorbar * `markersize` the size of the nodes * `markercolor` markercolor scheme * `markershape` shape of marker * `markerstrokewidth` width of marker stroke * `markerstrokealpha` capacity of marker stroke * `markervaluevaries` if the marker color depends on the signal value * `linewidth` the width of the lines in gplot * `linecolor` the color of the lines (1D) / graph edges (2D & 3D) * `linestyle`: the style of line * `notitle` display a title * `nocolorbar` display a colorbar * `nolegend` display a legend * `stemplot` use a stem plot * `clim` specify the dynamic display range * `sortnodes` plot the signal values from smallest to largest in magnitude """ function GraphSig_Plot(G::GraphSig; symmetric::Bool = false, markersize::Any = 2., markercolor::Symbol = :balance, markershape::Symbol = :circle, markerstrokewidth::Float64 = 1.0, markerstrokealpha::Float64 = 1.0, markervaluevaries::Bool = true, linewidth::Float64 = 1., linecolor::Symbol = :blue, linestyle::Symbol = :solid, clim::Tuple{Float64,Float64} = (0., 0.), notitle::Bool = false, nocolorbar::Bool = false, nolegend::Bool = true, stemplot::Bool = false, sortnodes::Symbol = :normal) # only run this for 1D signals fcols = Base.size(G.f, 2) if fcols == 0 G.f = zeros(G.length, 1) elseif fcols != 1 warn("Cannot handle multiple signals at this time!") return end ## Case 1: the graph does not have spatial coordinates or it is too large if G.length > 10^4 || G.dim > 3 || G.dim < 1 if G.length < 10^6 spy(G.W, show = true) # not too clear if we can change the dot size. scatter!((1:G.length)', (1:G.length)', marker=(:circle, 4), zcolor = G.f, title = G.name) else warn("Cannot handle a graph with more than 10^6 nodes at this time!") end return end ## Case 2: the graph does have spatial coordinates (G.dim = 1, 2, or 3). # extract the plot specifications # set(0, 'DefaultFigureVisible', 'on'); ################################# ############# 1-D ############### ################################# if G.dim == 1 if G.length < 65 || stemplot # stem(G.xy, G.f, '-o','LineWidth',2,'Color',linecolor,'MarkerFaceColor',linecolor,'MarkerSize',markersize(1)); # stem(G.xy, G.f, linetype = [:sticks :scatter], linewidth = 2, linecolor = linecolor, markercolor = linecolor, markersize = markersize) stem(G.f; x = G.xy, lw = linewidth, c = linecolor, ms = markersize, shape = markershape) else # plot(G.xy, G.f, '-','Color',linecolor,'LineWidth',linewidth); plot(G.xy, G.f, linetype = :line, linecolor = linecolor, linewidth = linewidth); end xmin = minimum(G.xy) xmax = maximum(G.xy) dx = xmax - xmin if dx < 10 * eps() dx = 1 end xmin = xmin - 0.1 * dx xmax = xmax + 0.1 * dx ymin = minimum(G.f) ymax = maximum(G.f) dy = ymax - ymin if dy < 10 * eps() dy = 1 end ymin = ymin - 0.1*dy ymax = ymax + 0.1*dy # symmetric? if symmetric ymax = 1.1 * max(ymax, -ymin) ymin = -ymax end xlims!(xmin, xmax) ylims!(ymin, ymax) # title? if ~isempty(G.name) && ~notitle title!(G.name) end # legend? if nolegend plot!(leg = false) end ################################# ######### 2-D or 3-D ########### ################################# else #fig = figure('visible','on'); # plot the graph gplot(G.W, G.xy; style = linestyle, color = linecolor, width = linewidth) #hold on # plot the nodes scatter_gplot!(G.xy; marker = G.f, ms = markersize, shape = markershape, mswidth = markerstrokewidth, msalpha = markerstrokealpha, plotOrder = sortnodes, c = markercolor) # colorbar? if nocolorbar plot!(colorbar = :none) end # custom dynamic display range? if clim != (0., 0.) plot!(clim = clim) end # symmetric? if symmetric if clim != (0., 0.) cmax = maximum(abs.(clim)); else cmax = maximum(abs.(G.f[:])); end if cmax < 10*eps() cmax = 1; end plot!(cLims = (cmax, cmax)) end # title? if !isempty(G.name) && !notitle title!(G.name); end # legend? if nolegend plot!(leg = false) end end end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
11491
module GraphSignal using Distances # This is necessary in Ggrid using Distributions # This is necessary in AddNoise using SparseArrays using Statistics using LinearAlgebra export GraphSig, replace_data!, snr, gpath, ggrid, Adj2InvEuc, AddNoise # GraphSig data structure and constructors """ G = GraphSig(W, xy, f, name, plotspecs, length, dim, size) is a data structure for a GraphSig object containing the following fields: * `W::SparseMatrixCSC{Float64,Int}`: the edge weight matrix in a sparse format * `xy::Matrix{Float64}`: the coordinates of the vertices (could be >= 3D) * `f::Matrix{Float64}`: the values of the function/data at the vertices; each column is an input signal vector, i.e., number of rows == number of nodes. * `name::String`: a title/name for the data * `plotspecs::Vector{Symbol}`: specifications for plotting: (most likely may be dropped later thanks to julia/Plots.jl) - symm: use a symmetric colorscale - gray: use grayscale - gray255: plot a grayscale image with color bounds [0,255] - copper: use a copper color scale - notitle: don't display the title - nocolorbar: don't display a colorbar - stem: use a stem plot - CLim[cmin,cmax]: set the dynamic display range to [cmin,cmax] - size25: set the size of the nodes to 25 (or whatever value is specified) - LineWidth2: set the width of the lines to 2 (or whatever value is specified) - LineColorb: set the color of the lines/graph edges to color 'b' (or whatever color is specified) - red/black/blue: make the nodes red, black, or blue - verbatim{{...}}: execute the command in the brackets """ mutable struct GraphSig W::SparseMatrixCSC{Float64,Int} # edge weight matrix xy::Matrix{Float64} # spatial coordinates (could be >= 3D) f::Matrix{Float64} # the data sequences (signals) on the nodes name::String # name of the GraphSig object plotspecs::String # special instructions for plotting # The following three are deriable from W, xy, and f: length::Int # length of the data sequence dim::Int # the dimension of the node coordinates size::Tuple{Int,Int} # size of all the data specified # An inner constructor here. function GraphSig(W::SparseMatrixCSC{Float64,Int}; xy::Matrix{Float64} = Matrix{Float64}(undef, 0, 0), f::Matrix{Float64} = zeros(Base.size(W, 1), 1), name::String = "", plotspecs :: String = "", #plotspecs::Vector{Symbol} = Vector{Symbol}(0), length::Int = Base.size(W, 1), dim::Int = Base.size(xy, 2), size::Tuple{Int,Int} = (Base.size(W, 1), Base.size(W, 2) + Base.size(xy, 2) + Base.size(f, 2))) # if isempty(W) error("Cannot setup a graph without an edge weight matrix W!") elseif Base.size(W, 1) != Base.size(f, 1) error("Signal length != # Nodes!!") elseif Base.size(W, 1) != Base.size(xy, 1) && Base.size(xy, 1) != 0 @warn("# Node coordinates != # Nodes. Hence, use null coordinates.") new( W, Matrix{Float64}(0, 0), f, name, plotspecs, Base.size(W, 1), 0, (Base.size(W, 1), Base.size(W, 2) + Base.size(f, 2)) ) else # Finally, the full constructor! new( W, xy, f, name, plotspecs, Base.size(W, 1), Base.size(xy, 2), (Base.size(W, 1), Base.size(W, 2) + Base.size(xy, 2) + Base.size(f, 2)) ) end end # of the inner constructor end # of type GraphSig # # Other GraphSig related functions # """ replace_data!(G::GraphSig, newdata::Matrix{Float64}) Replace the data in a GraphSig object ### Input Arguments * `G::GraphSig`: the input GraphSig object whose data is to be replaced; various fields are updated after execution of this function * `newdata::Matrix{Float64}`: the new data (must be a matrix) """ function replace_data!(G::GraphSig, newdata::Matrix{Float64}) (rows, cols) = Base.size(newdata) if G.length == rows # update the relevant fields accordingly G.f = newdata G.size = (rows, Base.size(G.W, 2) + Base.size(G.xy, 2) + cols) else error("The length of each signal (", rows, ") does not match the number of nodes (", G.length, ")!") # elseif G.length == cols # This is a dangerous assumption; so prohibit it. # G.f = newdata' # elseif isscalar(newdata) # This does not work anymore unlike MATLAB # G.f = newdata*ones(G.length, 1) end end # of function replace_data! """ (value, sigma) = snr(G1::GraphSig, G2::GraphSig, stdp::Bool = false) Compute the SNR between G1 (original signal) and G2 (noisy signal) ### Input Arguments * `G1::GraphSig`: Original reference graph signal * `G2::GraphSig`: Restored or noisy graph signal * `stdp::Bool`: A flag to specify to compute the standard deviation of the difference ### Output Arguments * `value`: Signal/Noise Ratio in the dB unit * `sigma`: the standard deviation of the noise (if stdp == true) """ function snr(G1::GraphSig, G2::GraphSig, stdp=false) tmp = norm(G2.f - G1.f) if tmp < 10 * eps() @warn("Two signals are the same, hence SNR = Inf") value = Inf else value = 20 * log10(norm(G1.f) / tmp) end if stdp return value, std(G2.f - G1.f) else return value end end # of snr """ G = gpath(N, f, name) Generate a GraphSig object for a 1-D path of length `N` ### Input Arguments * `N::Int`: the length of the path * `f::Matrix{Float64}`: the signal to be used * `name::String`: the name for the GraphSig object ### Output Argument * `G::GraphSig`: the GraphSig ojbect representing the 1-D path of length `N` """ function gpath(N::Int, f::Matrix{Float64} = ones(N, 1), name::String = "Path of length $(N)") # the x coordinates xy = Matrix{Float64}(reshape(1:N, N, 1)) # another option: xy = (1.0:Float64(N))[:,:] # the weight matrix ev = ones(N - 1) # subdiagonal entries W = spdiagm(-1 => ev, 1 => ev) #W = spdiagm((ev, ev), (-1, 1)) # size(W) is (N, N) # MATLAB: # ev = ones(N,1); # W = spdiags([ev 0*ev ev], [-1 0 1], N, N); # create and return the GraphSig object return GraphSig(W, xy = xy, f = f, name = name) end # of function gpath """ function ggrid(Nx::Int, Ny::Int, connect::Symbol) Generate a GraphSig object for a 2-D grid that is `Nx` by `Ny`. ### Input Arguments * `Nx::Int`: the number of points in the x direction * `Ny::Int`: the number of points in the y direction * `connect::Symbol`: specifies the connectivity mode of the 2-D grid: choices are: :c4 (default), :c8, :full ### Output Argument * `G::GraphSig`: the GraphSig ojbect representing the 2-D `Nx` by `Ny` grid. """ function ggrid(Nx::Int, Ny::Int, connect::Symbol = :c4) # the total number of nodes N = Nx * Ny # the xy coordinates # MATLAB: # xy = [(1:N)', repmat((1:Ny)',Nx,1)]; # xy(:,1) = ceil(xy(:,1)/Ny); xy =hcat( ceil.(collect(1:N) / Ny), repeat(1:Ny, Nx) ) if connect == :c4 # this is the default, i.e., l; r; u; d. # make 1-D weight matrices ex = ones(Nx - 1) Wx = spdiagm(-1 => ex, 1 => ex) #Wx = spdiagm((ex, ex), (-1, 1)) ey = ones(Ny - 1) Wy = spdiagm(-1 => ey, 1 => ey) #Wy = spdiagm((ey, ey), (-1, 1)) # form the 2-D weight matrix W = kron(sparse(1.0I, Nx, Nx), Wy) + kron(Wx, sparse(1.0I, Ny, Ny)) # this keeps a sparse form else # now for 8-connected or fully-connected cases W = sparse(pairwise(Euclidean(), xy')) # This is from Distances package. W[1:(N + 1):(N * N)] = 10 # set each diagonal entry to 10 to prevent blowup. W = W.^-1 # convert dist to affinity = inv. dist. if connect == :c8 # 8-connected case incl. diagonal connections W[find(W .< 0.7)] = 0 elseif connect == :full # a complete graph case W[1:(N + 1):(N * N)] = 0 # set the diagonal to zero (i.e., no loops) else error("Cannot understand this connectivity: ", connect) end end return GraphSig(W, xy = xy, f = Matrix{Float64}((1:N)[:, :]), name = "$(Nx) by $(Ny) grid with connectivity mode $(connect)") end # of function ggrid """ function Adj2InvEuc(G::GraphSig) Given a GraphSig object 'G' with a binary weight (adjacency) matrix, generate a GraphSig object 'GInvEuc' with an inverse Euclidean distance matrix ### Input Arguments * `G::GraphSig`: a GraphSig object ### Output Argument * `G::GraphSig`: a GraphSig object with inverse Euclidean weights """ function Adj2InvEuc(G::GraphSig) W = deepcopy(G.W) xy = deepcopy(G.xy) f = deepcopy(G.f) #find the edges (rows,cols) = findnz(W) #remove duplicate points for j = length(rows):-1:1 if j<=length(rows) && norm(xy[rows[j],:]-xy[cols[j],:],2) < 10^3*eps() W = W[setdiff(1:end, rows[j]), :] W = W[:, setdiff(1:end, rows[j])] xy = xy[setdiff(1:end, rows[j]), :] f = f[setdiff(1:end, rows[j]),:] (rows,cols) = findnz(W) end end for j = 1:length(rows) W[rows[j],cols[j]] = 1/norm(xy[rows[j],:]-xy[cols[j],:],2) end return GraphSig(W, xy = xy, f = f, name = string(G.name, " (inverse Euclidean weight matrix)"), plotspecs = G.plotspecs) end """ function AddNoise(G::GraphSig; SNR::Float64=Float64(1.24), noisetype::String = "gaussian") Add noise to the data of a GraphSig object ### Input Arguments * `G::GraphSig`: a GraphSig object * `SNR`: the SNR that the noisy signal should have * `noisetype`: the type of noise: Gaussian (default) or Poisson ### Output Argument * `G::GraphSig`: the GraphSig object with added noise * `sigma`: the standard deviation of the noise """ function AddNoise(G::GraphSig; SNR::Float64=Float64(1.24), noisetype::String = "gaussian") f = deepcopy(G.f) if noisetype == "gaussian" # generate Gaussian noise noise = randn(size(f)) # scale the noise to the desired SNR level sigma = norm(f,2)/10.0^(0.05*SNR)/norm(noise,2) noise = sigma*noise # generate the noisy signal f = f + noise elseif noisetype == "poisson" # generate Poisson noise (rows,cols) = size(f) noise = zeros(rows,cols) for i = 1:rows for j = 1:cols noise[i,j] = rand(Poisson(f[i,j])) - f[i,j] end end # scale the noise to the desired SNR level sigma = norm(f,2)/10.0^(0.05*SNR)/norm(noise,2) noise = sigma*noise # generate the noisy signal f = f + noise end return GraphSig(G.W, xy = G.xy, f = f, name = string("SNR = ",SNR," ", G.name), plotspecs = G.plotspecs) end end # of module GraphSignal
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
30234
module HGLET include("utils.jl") using ..GraphSignal, ..GraphPartition, ..BasisSpecification, ..GHWT, SparseArrays include("common.jl") export HGLET_Synthesis, HGLET_jkl, HGLET_Analysis, HGLET_Analysis_All, HGLET_BestBasis, HGLET_GHWT_BestBasis, HGLET_GHWT_Synthesis, HGLET_GHWT_BestBasis_minrelerror """ function HGLET_Synthesis(dvec::Vector{Float64}, GP::GraphPart, BS::BasisSpec, G::GraphSig; gltype::Symbol = :L) ### Input Arguments * `dvec`: the expansion coefficients corresponding to the chosen basis * `GP`: a GraphPart object * `BS`: a BasisSpec object * `G`: a GraphSig object * `gltype`: :L, :Lrw, or :Lsym, indicating which eigenvectors are used ### Output Argument * `f`: the reconstructed signal * `GS`: the reconstructed GraphSig object """ function HGLET_Synthesis(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec, G::GraphSig; gltype::Symbol = :L) # Preliminaries W = G.W jmax = size(GP.rs,2) # Fill in the appropriate entries of dmatrix dmatrix = dvec2dmatrix(dvec,GP,BS) f = dmatrix[:,jmax,:] # Perform the signal synthesis from the given coefficients for j = jmax:-1:1 regioncount = count(!iszero, GP.rs[:,j]) - 1 for r = 1:regioncount # the index that marks the start of the region rs1 = GP.rs[r,j] # the index that is one after the end of the region rs3 = GP.rs[r+1,j] # the number of points in the current region n = rs3 - rs1 # only proceed forward if coefficients do not exist if (j == jmax || count(!iszero, dmatrix[rs1:rs3-1,j+1,:]) == 0) && count(!iszero, dmatrix[rs1:rs3-1,j,:]) > 0 if n == 1 f[rs1,:] = dmatrix[rs1,j,:] elseif n > 1 indrs = GP.ind[rs1:rs3-1] W_temp = W[indrs,indrs] D = Diagonal(vec(sum(W_temp, dims = 1))) D2 =Diagonal(vec(sum(W_temp, dims = 1)).^(-0.5)) normalizep = false # a flag for normalizing L for Lsym/Lrw if minimum(diag(D)) > 10^3*eps() # avoiding 1/small entries normalizep = true end # compute the GL eigenvectors via svd. if ( gltype == :Lrw || gltype == :Lsym ) && normalizep v,_,_ = svd(D2 * (D - Matrix(W_temp)) * D2) else v,_,_ = svd(D - Matrix(W_temp)) if gltype != :L @warn("Due to the small diagonal entries of W, we revert back to the option :L, not :" * String(gltype)) end end v = v[:,end:-1:1] # reorder the ev's in the decreasing ew's # standardize the eigenvector signs for col = 1:n row = 1 standardized = false while !standardized if v[row,col] > 10^3*eps() standardized = true elseif v[row,col] < -10^3*eps() v[:,col] = - v[:,col] standardized = true else row += 1 end end end # reconstruct the signal if gltype == :Lrw && normalizep f[rs1:rs3-1,:] = D2*v*dmatrix[rs1:rs3-1,j,:] else f[rs1:rs3-1,:] = v*dmatrix[rs1:rs3-1,j,:] end end end end end # put the reconstructed values in the correct order f[GP.ind,:] = f # creat a GraphSig object with the reconstructed data GS = deepcopy(G) replace_data!(GS,f) return f, GS end """ function HGLET_jkl(GP::GraphPart, drow::Int, dcol::Int) Generate the (j,k,l) indices for the HGLET basis vector corresponding to the coefficient dmatrix(drow,dcol) ### Input Arguments * `GP`: a GraphPart object * `drow`: the row of the expansion coefficient * `dcol`: the column of the expansion coefficient ### Output Argument * `j`: the level index of the expansion coefficient * `k`: the subregion index of the expansion coefficient * `l`: the eigenvector index of the expansion coefficient """ function HGLET_jkl(GP::GraphPart, drow::Int, dcol::Int) j = dcol - 1 k = findfirst(GP.rs[:,dcol] .> drow) k = k-2 l = drow - GP.rs[k+1,dcol] return j,k,l end """ function HGLET_Analysis(G::GraphSig, GP::GraphPart, gltype::Symbol = :L) For a GraphSig object 'G', generate the matrix of HGLET expansion coefficients corresponding to the eigenvectors of specified version of the graph Laplacian matrix, i.e., either L, Lrw, or Lsym ### Input Arguments * `G`: a GraphSig object * `GP`: a GraphPart object * `gltype`: :L, :Lrw, or :Lsym, indicating which eigenvectors are used ### Output Argument * `dmatrix`: the matrix of expansion coefficients using the specific GL matrix """ function HGLET_Analysis(G::GraphSig, GP::GraphPart, gltype::Symbol = :L) # Preliminaries W = G.W ind = GP.ind rs = GP.rs N = size(G.W,1) jmax = size(rs,2) fcols = size(G.f,2) dmatrix = zeros(N,jmax,fcols) dmatrix[:,jmax,:] = G.f[ind,:] # Perform the HGLET analysis, i.e., generating the HGLET coefficients for j = jmax-1:-1:1 regioncount = count(!iszero, rs[:,j]) - 1 for r = 1:regioncount # the index that marks the start of the region rs1 = rs[r,j] # the index that is one after the end of the region rs3 = rs[r+1,j] # the number of points in the current region n = rs3 - rs1 if n == 1 dmatrix[rs1,j,:] = G.f[ind[rs1],:] elseif n > 1 indrs = ind[rs1:rs3-1] W_temp = W[indrs,indrs] D = Diagonal(vec(sum(W_temp, dims = 1))) D2 = Diagonal(vec(sum(W_temp, dims = 1)).^(-0.5)) normalizep = false # a flag for normalizing L for Lsym and Lrw if minimum(diag(D)) > 10^3*eps() # avoiding 1/small entries normalizep = true end # compute the GL eigenvectors via svd if ( gltype == :Lrw || gltype == :Lsym ) && normalizep v,_,_ = svd(D2 * (D - Matrix(W_temp)) * D2) else v,_,_ = svd(D - Matrix(W_temp)) if gltype != :L @warn("Due to the small diagonal entries of W, we revert back to the option :L, not :" * String(gltype)) end end v = v[:,end:-1:1] # reorder the ev's in the decreasing ew's # standardize the eigenvector signs for col = 1:n row = 1 standardized = false while !standardized if v[row,col] > 10^3*eps() standardized = true elseif v[row,col] < -10^3*eps() v[:,col] = - v[:,col] standardized = true else row += 1 end end end # obtain the expansion coeffcients if gltype == :Lrw && normalizep dmatrix[rs1:rs3-1,j,:] = v'*(D.^0.5)*G.f[indrs,:] else dmatrix[rs1:rs3-1,j,:] = v'*G.f[indrs,:] end end end end return dmatrix end """ function HGLET_Analysis_All(G::GraphSig, GP::GraphPart) For a GraphSig object 'G', generate the 3 matrices of HGLET expansion coefficients corresponding to the eigenvectors of L, Lrw and Lsym ### Input Arguments * `G`: a GraphSig object * `GP`: a GraphPart object ### Output Argument * `dmatrixH`: the matrix of expansion coefficients for L * `dmatrixHrw`: the matrix of expansion coefficients for Lrw * `dmatrixHsym`: the matrix of expansion coefficients for Lsym """ function HGLET_Analysis_All(G::GraphSig, GP::GraphPart) # Preliminaries W = G.W ind = GP.ind rs = GP.rs # This is the type of graph Laplacian matrix used for graph partitioning; # Not the eigenvector dictionary computed for the HGLET. method = GP.method N = size(G.W,1) jmax = size(rs,2) fcols = size(G.f,2) dmatrixH = zeros(N,jmax,fcols) dmatrixH[:,jmax,:] = G.f[ind,:] dmatrixHrw = deepcopy(dmatrixH) dmatrixHsym = deepcopy(dmatrixH) # Perform the transform ==> eigenvectors of L for j = jmax-1:-1:1 regioncount = count(!iszero, rs[:,j]) - 1 for r = 1:regioncount # the index that marks the start of the region rs1 = rs[r,j] # the index that is one after the end of the region rs3 = rs[r+1,j] # the number of points in the current region n = rs3-rs1 if n == 1 dmatrixH[rs1,j,:] = G.f[ind[rs1],:] elseif n > 1 indrs = ind[rs1:rs3-1] # compute the eigenvectors of L ==> svd(L) v,_,_ = svd(Diagonal(vec(sum(W[indrs,indrs],dims = 1))) - Matrix(W[indrs,indrs])) v = v[:,end:-1:1] # standardize the eigenvector signs for col = 1:n row = 1 standardized = false while !standardized if v[row,col] > 10^3*eps() standardized = true elseif v[row,col] < -10^3*eps() v[:,col] = - v[:,col] standardized = true else row += 1 end end end # obtain the expansion coefficients dmatrixH[rs1:rs3-1,j,:] = v'*G.f[indrs,:] end end end for j = jmax-1:-1:1 regioncount = count(!iszero, rs[:,j])-1 for r = 1:regioncount # the index that marks the start of the region rs1 = rs[r,j] # the index that is one after the end of the region rs3 = rs[r+1,j] # the number of points in the current region n = rs3 - rs1 if n == 1 dmatrixHrw[rs1,j,:] = G.f[ind[rs1],:] dmatrixHsym[rs1,j,:] = G.f[ind[rs1],:] elseif n > 1 indrs = ind[rs1:rs3-1] # compute the eigenvectors if minimum(sum(W[indrs,indrs],dims = 1)) > 10^3*eps() useLrw = true ### eigenvectors of L_rw ==> svd(L_sym) W_temp = W[indrs,indrs] D = Diagonal(vec(sum(W_temp,dims = 1))) D2 =Diagonal(vec(sum(W_temp,dims = 1)).^(-0.5)) v,_,_ = svd(D2 * (D - Matrix(W_temp)) * D2) v = v[:,end:-1:1] else useLrw = false ### eigenvectors of L ==> svd(L) W_temp = W[indrs,indrs] D = Diagonal(vec(sum(W_temp,dims = 1))) v,_,_ = svd(D - Matrix(W_temp)) v = v[:,end:-1:1] end #standardized the eigenvector signs for col = 1:n row = 1 standardized = false while !standardized if v[row,col] > 10^3*eps() standardized = true elseif v[row,col] < -10^3*eps() v[:,col] = - v[:,col] standardized = true else row += 1 end end end # obtain the expansion coefficients for L_sym dmatrixHsym[rs1:rs3-1,j,:] = v'*G.f[indrs,:] # obtain the expansion coeffcients for L_rw if useLrw dmatrixHrw[rs1:rs3-1,j,:] = v'*(Diagonal(vec(sum(W_temp,dims = 1)).^0.5))*G.f[indrs,:] else dmatrixHrw[rs1:rs3-1,j,:] = v'*G.f[indrs,:] end end end end return dmatrixH, dmatrixHrw, dmatrixHsym end """ function HGLET_BestBasis(GP::GraphPart; dmatrix::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), gltype::Symbol = :L, cfspec::Any = 0.1, flatten::Any = 1) Select the HGLET best basis from the input matrix of expansion coefficients ### Input Arguments * `GP`: a GraphPart object * `dmatrix`: the matrix of HGLET expansion coefficients * `gltype`: the type of graph Laplacian matrix used for HGLET dictionary (default = :L) * `cfspec`: the cost functional specification to be used: see utils.jl for the detail. If it's a number, say, p, then the l^p norm is used. If it's a function, then that function is used. Default is 0.1, i.e., l^0.1 * `flatten`: the method for flattening vector-valued data to scalar-valued data; If it's a number, say, p, then the sum of the l^p norm is computed. There are many other options, such as :ash, :entropy, etc. See utils.jl for the detail. Default is 1, i.e, the sum of the l^1 norm of the coefs. ### Output Argument * `dvec`: the vector of expansion coefficients corresponding to the bestbasis * `BS`: a BasisSpec object which specifies the best basis """ function HGLET_BestBasis(GP::GraphPart; dmatrix::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), gltype::Symbol = :L, cfspec::Any = 0.1, flatten::Any = 1) # the cost functional to be used costfun = cost_functional(cfspec) # constants and dmatrix cleanup N, jmax, fcols = size(dmatrix) dmatrix[abs.(dmatrix) .< 10^2*eps()] .= 0 # flatten dmatrix for more than one input signals if fcols > 1 dmatrix0 = deepcopy(dmatrix) dmatrix = dropdims(dmatrix_flatten(dmatrix, flatten), dims = 3) end # # Find the HGLET best basis now! # # allocate/initialize ==> order matters here dvec = dmatrix[:,jmax] levlist = jmax*ones(Int,N) # set the tolerance tol = 10^4*eps() # perform the basis search for j = jmax:-1:1 regioncount = count(!iszero, GP.rs[:,j]) - 1 for r = 1:regioncount indr = GP.rs[r,j]:(GP.rs[r+1,j]-1) ### compute the cost of the current best basis costBB = costfun(dvec[indr]) ### compute the cost of the HGLET coefficients costNew = costfun(dmatrix[indr,j]) # change the best basis if the new cost is less expensive if costBB >= costNew - tol costBB, dvec[indr], levlist[indr] = BBchange(costNew, dmatrix[indr,j], j) end end end levlist = collect(enumerate(levlist)) BS = BasisSpec(levlist, c2f = true, description = "HGLET Best Basis") #levlist2levlengths!(GP, BS) # if we flattened dmatrix, then "unflatten" the expansion coefficients if fcols > 1 dvec = dmatrix2dvec(dmatrix0, GP, BS) end return dvec, BS end """ function HGLET_GHWT_BestBasis(GP::GraphPart; dmatrixH::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHrw::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHsym::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixG::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), cfspec::Any = 0.1,flatten::Any = 1) Select the best basis from several matrices of expansion coefficients ### Input Arguments * `dmatrixH`: the matrix of HGLET expansion coefficients ==> eigenvectors of L * `dmatrixHrw`: the matrix of HGLET expansion coefficients ==> eigenvectors of Lrw * `dmatrixHsym`: the matrix of HGLET expansion coefficients ==> eigenvectors of Lsym * `dmatrixG`: the matrix of GHWT expansion coefficients * `GP`: a GraphPart object * `cfspec`: the cost functional specification to be used: see utils.jl for the detail. If it's a number, say, p, then the l^p norm is used. If it's a function, then that function is used. Default is 0.1, i.e., l^0.1 * `flatten`: the method for flattening vector-valued data to scalar-valued data; If it's a number, say, p, then the sum of the l^p norm is computed. There are many other options, such as :ash, :entropy, etc. See utils.jl for the detail. Default is 1, i.e, the sum of the l^1 norm of the coefs. ### Output Argument * `dvec`: the vector of expansion coefficients corresponding to the bestbasis * `BS`: a BasisSpec object which specifies the best basis * `trans`: specifies which transform was used for that portion of the signal: 00 = HGLET with L 01 = HGLET with Lrw 10 = HGLET with Lsym 11 = GHWT """ function HGLET_GHWT_BestBasis(GP::GraphPart; dmatrixH::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHrw::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHsym::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixG::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), cfspec::Any = 0.1,flatten::Any = 1) # specify transform codes transHsym = [true false] transG = [true true] transHrw = [false true] transH = [false false] # the cost functional to be used costfun = cost_functional(cfspec) # constants and dmatrix cleanup if !isempty(dmatrixHsym) N, jmax, fcols = size(dmatrixHsym) dmatrixHsym[abs.(dmatrixHsym).<10^2*eps()] .= 0 end if !isempty(dmatrixG) N, jmax, fcols = size(dmatrixG) dmatrixG[abs.(dmatrixG).<10^2*eps()] .= 0 end if !isempty(dmatrixHrw) N, jmax, fcols = size(dmatrixHrw) dmatrixHrw[abs.(dmatrixHrw).<10^2*eps()] .= 0 end if !isempty(dmatrixH) N, jmax, fcols = size(dmatrixH) dmatrixH[abs.(dmatrixH).<10^2*eps()] .= 0 end # flatten dmatrix if fcols > 1 if !isempty(dmatrixHsym) dmatrix0Hsym = deepcopy(dmatrixHsym) dmatrixHsym = dropdims(dmatrix_flatten(dmatrixHsym,flatten),dims = 3) end if !isempty(dmatrixG) dmatrix0G = deepcopy(dmatrixG) dmatrixG = dropdims(dmatrix_flatten(dmatrixG,flatten),dims = 3) end if !isempty(dmatrixHrw) dmatrix0Hrw = deepcopy(dmatrixHrw) dmatrixHrw = dropdims(dmatrix_flatten(dmatrixHrw,flatten),dims = 3) end if !isempty(dmatrixH) dmatrix0H = deepcopy(dmatrixH) dmatrixH = dropdims(dmatrix_flatten(dmatrixH,flatten),dims = 3) end end # Find the HGLET/GHWT best basis # allocate/initialize ==> order matters here if !isempty(dmatrixHsym) dvec = dmatrixHsym[:,jmax] trans = repeat(transHsym,N,1) end if !isempty(dmatrixG) dvec = dmatrixG[:,jmax] trans = repeat(transG,N,1) end if !isempty(dmatrixHrw) dvec = dmatrixHrw[:,jmax] trans = repeat(transHrw,N,1) end if !isempty(dmatrixH) dvec = dmatrixH[:,jmax] trans = repeat(transH,N,1) end levlist = jmax*ones(Int,N) # set the tolerance tol = 10^4*eps() # perform the basis search for j = jmax:-1:1 regioncount = count(!iszero, GP.rs[:,j]) - 1 for r = 1:regioncount indr = GP.rs[r,j]:(GP.rs[r+1,j]-1) ### compute the cost of the current best basis costBB = costfun(dvec[indr]) ### compute the cost of the HGLET-Lsym coefficients if !isempty(dmatrixHsym) costNew = costfun(dmatrixHsym[indr,j]) # change the best basis if the new cost is less expensive if costBB >= costNew - tol costBB, dvec[indr], levlist[indr], trans[indr,:] = BBchange(costNew, dmatrixHsym[indr,j],j,transHsym) end end ### compute the cost of the GHWT coefficients if !isempty(dmatrixG) costNew = costfun(dmatrixG[indr,j]) # change the best basis if the new cost is less expensive if costBB >= costNew - tol costBB, dvec[indr], levlist[indr], trans[indr,:] = BBchange(costNew, dmatrixG[indr,j],j,transG) end end ### compute the cost of the HGLET-Lrw coefficients if !isempty(dmatrixHrw) costNew = costfun(dmatrixHrw[indr,j]) # change the best basis if the new cost is less expensive if costBB >= costNew - tol costBB, dvec[indr], levlist[indr], trans[indr,:] = BBchange(costNew, dmatrixHrw[indr,j],j,transHrw) end end ### compute the cost of the HGLET-L coefficients if !isempty(dmatrixH) costNew = costfun(dmatrixH[indr,j]) # change the best basis if the new cost is less expensive if costBB >= costNew - tol _, dvec[indr],levlist[indr],trans[indr,:] = BBchange(costNew, dmatrixH[indr,j],j,transH) end end end end transfull = deepcopy(trans) #trans = trans[levlist.!=0,:] levlist = collect(enumerate(levlist)) BS = BasisSpec(levlist,c2f = true, description = "HGLET-GHWT Best Basis") #levlist2levlengths!(GP,BS) # if we flattened dmatrix, then "unflatten" the expansion coefficients if fcols > 1 # create vectors of coefficients (which are zero if the transform's coefficients were not included as function inputs) if !isempty(dmatrixH) dvecH = dmatrix2dvec(dmatrix0H,GP,BS) else dvecH = zeros(N,fcols) end if !isempty(dmatrixHrw) dvecHrw = dmatrix2dvec(dmatrix0Hrw,GP,BS) else dvecHrw = zeros(N,fcols) end if !isempty(dmatrixHsym) dvecHsym = dmatrix2dvec(dmatrix0Hsym,GP,BS) else dvecHsym = zeros(N,fcols) end if !isempty(dmatrixG) dvecG = dmatrix2dvec(dmatrix0G,GP,BS) else dvecG = zeros(N,fcols) end dvec = dvecHsym.*(transfull[:,1].*(.~transfull[:,2])) + dvecG.*(transfull[:,1].*transfull[:,2]) + dvecHrw.*((.~transfull[:,1]).*transfull[:,2]) + dvecH.*((.~transfull[:,1]).*(.~transfull[:,2])) end return dvec, BS, transfull end function BBchange(costNew::Float64, dvec::Vector{Float64}, j::Int) #change to the new best basis costBB = costNew n = length(dvec) levlist = fill(j, n) return costBB, dvec, levlist end function BBchange(costNew::Float64, dvec::Vector{Float64}, j::Int, trans::Array{Bool,2}) #change to the new best basis costBB = costNew n = length(dvec) levlist = fill(j, n) trans = repeat(trans,n,1) return costBB, dvec, levlist, trans end """ function HGLET_GHWT_Synthesis(dvec::Matrix{Float64},GP::GraphPart,BS::BasisSpec,trans::Array{Bool,2},G::GraphSig) Given a vector of HGLET & GHWT expansion coefficients, info about the graph partitioning, and the choice of basis and corresponding transforms, reconstruct the signal. ### Input Arguments * `dvec`: the expansion coefficients corresponding to the chosen basis * `GP`: a GraphPart object * `BS`: a BasisSpec object * `trans`: a specification of the transforms used for the HGLET-GHWT hybrid transform 00 = HGLET with L 01 = HGLET with Lrw 10 = HGLET with Lsym 11 = GHWT * `G`: a GraphSig object ### Output Argument * `f`: the reconstructed signal * `GS`: the reconstructed GraphSig object """ function HGLET_GHWT_Synthesis(dvec::Matrix{Float64},GP::GraphPart,BS::BasisSpec,trans::Array{Bool,2},G::GraphSig) # fill out trans #_,_,transfull = BSfull(GP,BS,trans) transfull = trans # decompose dvec into GHWT and HGLET components dvecHsym= dvec.*(transfull[:,1].*(.~transfull[:,2])) dvecG = dvec.*(transfull[:,1].*transfull[:,2]) dvecHrw = dvec.*((.~transfull[:,1]).*transfull[:,2]) dvecH = dvec.*((.~transfull[:,1]).*(.~transfull[:,2])) # Synthesize using the transforms separately fH,_ = HGLET_Synthesis(dvecH, GP, BS, G) fHrw,_ = HGLET_Synthesis(dvecHrw, GP, BS, G, gltype = :Lrw) fHsym,_ = HGLET_Synthesis(dvecHsym, GP, BS, G, gltype = :Lsym) fG = ghwt_synthesis(dvecG, GP, BS) f = fH + fHrw + fHsym + fG GS = deepcopy(G) replace_data!(GS,f) return f, GS end """ function HGLET_GHWT_BestBasis_minrelerror(GP::GraphPart, G::GraphSig; dmatrixH::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHrw::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHsym::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixG::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), compare::Bool = true) Find the best basis for approximating the signal 'G' by performing the best basis search with a range of tau-measures as cost functionals (tau = 0.1,0.2,...,1.9) and minimizing the relative error. ### Input argument: * `dmatrixH`: the matrix of HGLET expansion coefficients ==> eigenvectors of L * `dmatrixHrw`: the matrix of HGLET expansion coefficients ==> eigenvectors of Lrw * `dmatrixHsym`: the matrix of HGLET expansion coefficients ==> eigenvectors of Lsym * `dmatrixG`: the matrix of GHWT expansion coefficients * `GP`: a GraphPart object * `G`: the GraphSig object * `compare`: if it is false, don't compare the hybrid best basis to the GHWT fine-to-coarse best basis ### Output argument: * `dvec`: the vector of expansion coefficients corresponding to the bestbasis * `BS`: a BasisSpec object which specifies the best basis * `trans`: specifies which transform was used for that portion of the signal 00 = HGLET with L 01 = HGLET with Lrw 10 = HGLET with Lsym 11 = GHWT * `tau`: the tau that yields the smallest relative error """ function HGLET_GHWT_BestBasis_minrelerror(GP::GraphPart, G::GraphSig; dmatrixH::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHrw::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixHsym::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), dmatrixG::Array{Float64,3} = Array{Float64,3}(undef,0,0,0), compare::Bool = true) dvec, BS, trans, tau = 0, 0, 0, 0 # predefine sumrelerror = Inf for tau_temp = 0.1:0.1:1.9 # we are only considering the GHWT if isempty(dmatrixH) && isempty(dmatrixHrw) && isempty(dmatrixHsym) && !isempty(dmatrixG) dvec_temp, BS_temp = ghwt_bestbasis(dmatrixG, GP, cfspec = tau_temp) trans_temp = trues(length(BS_temp.levlist),2) orthbasis = true else dvec_temp, BS_temp, trans_temp = HGLET_GHWT_BestBasis(GP, dmatrixH = dmatrixH, dmatrixG = dmatrixG, dmatrixHrw = dmatrixHrw, dmatrixHsym = dmatrixHsym, cfspec = tau_temp) # check whether any HGLET Lrw basis vectors are in the best basis orthbasis = true rows = size(trans_temp,1) for row = 1:rows if !trans_temp[row,1] && trans_temp[row,2] orthbasis = false break end end end # compute the relative errors if orthbasis relerror_temp = orth2relerror(dvec_temp[:]) else B,_ = HGLET_GHWT_Synthesis(Matrix{Float64}(I,length(dvec_temp),length(dvec_temp)), GP, BS_temp, trans_temp, G) relerror_temp = nonorth2relerror(dvec_temp[:],B) end sumrelerror_temp = sum(relerror_temp) # consider the GHWT fine-to-coarse best basis if compare == true && !isempty(dmatrixG) dvec_f2c, BS_f2c = ghwt_f2c_bestbasis(dmatrixG, GP, cfspec = tau_temp) sumrelerror_f2c = sum(orth2relerror(dvec_f2c[:])) if sumrelerror_f2c < sumrelerror_temp sumrelerror_temp = sumrelerror_f2c dvec_temp = copy(dvec_f2c) BS_temp = deepcopy(BS_f2c) trans_temp = repeat([true true], length(BS_f2c.levlist),1) end end # compare to the current lowest sum of relative errors if sumrelerror_temp < sumrelerror dvec = copy(dvec_temp) BS = deepcopy(BS_temp) trans = copy(trans_temp) sumrelerror = sumrelerror_temp tau = tau_temp end end return dvec, BS, trans, tau end end # end of module HGLET
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
7502
""" function LPHGLET_Synthesis(dvec::Vector{Float64}, GP::GraphPart, BS::BasisSpec, G::GraphSig; gltype::Symbol = :L, ϵ::Float64 = 0.3) Perform Lapped-HGLET Synthesis transform ### Input Arguments * `dvec`: the expansion coefficients corresponding to the chosen basis * `GP`: a GraphPart object * `BS`: a BasisSpec object * `G`: a GraphSig object * `gltype`: :L or :Lsym, indicating which eigenvectors are used * `ϵ`: relative action bandwidth (default: 0.3) ### Output Argument * `f`: the reconstructed signal * `GS`: the reconstructed GraphSig object """ function LPHGLET_Synthesis(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec, G::GraphSig; gltype::Symbol = :L, ϵ::Float64 = 0.3) # Preliminaries W = G.W inds = GP.inds rs = GP.rs N = size(W, 1) jmax = size(rs, 2) Uf = Matrix{Float64}(I, N, N) used_node = Set() # fill in the appropriate entries of dmatrix dmatrix = dvec2dmatrix(dvec, GP, BS) f = zeros(size(dmatrix[:, jmax, :])) # Perform the synthesis transform for j = 1:jmax regioncount = count(!iszero, rs[:,j]) - 1 # assemble orthogonal folding operator at level j - 1 keep_folding!(Uf, used_node, W, GP; ϵ = ϵ, j = j - 1) for r = 1:regioncount # indices of current region indr = rs[r, j]:(rs[r + 1, j] - 1) # indices of current region's nodes indrs = inds[indr, j] # number of nodes in current region n = length(indrs) # only proceed forward if coefficients do not exist if (j == jmax || count(!iszero, dmatrix[indr, j + 1, :]) == 0) && count(!iszero, dmatrix[indr, j, :]) > 0 # compute the eigenvectors W_temp = W[indrs,indrs] D_temp = Diagonal(vec(sum(W_temp, dims = 1))) if gltype == :L # compute the eigenvectors of L ==> svd(L) v = svd(Matrix(D_temp - W_temp)).U elseif gltype == :Lsym # check if one can assemble the Lsym if minimum(sum(W[indrs, indrs], dims = 1)) > 10^3 * eps() ### eigenvectors of L_sym ==> svd(L_sym) D_temp_p = Diagonal(vec(sum(W_temp, dims = 1)).^(-0.5)) v = svd(Matrix(D_temp_p * (D_temp - W_temp) * D_temp_p)).U else ### eigenvectors of L ==> svd(L) v = svd(Matrix(D_temp - W_temp)).U end end v = v[:,end:-1:1] # standardize the eigenvector signs standardize_eigenvector_signs!(v) # construct unfolder operator custom to current region P = Uf[indrs, :]' # reconstruct the signal f += (P * v) * dmatrix[indr, j, :] end end end # creat a GraphSig object with the reconstructed data GS = deepcopy(G) replace_data!(GS, f) return f, GS end """ function LPHGLET_Analysis_All(G::GraphSig, GP::GraphPart; ϵ::Float64 = 0.3) For a GraphSig object 'G', generate the 2 matrices of Lapped-HGLET expansion coefficients corresponding to the eigenvectors of L and Lsym ### Input Arguments * `G`: a GraphSig object * `GP`: a GraphPart object * `ϵ`: relative action bandwidth (default: 0.3) ### Output Argument * `dmatrixlH`: the matrix of expansion coefficients for L * `dmatrixlHsym`: the matrix of expansion coefficients for Lsym * `GP`: a GraphPart object """ function LPHGLET_Analysis_All(G::GraphSig, GP::GraphPart; ϵ::Float64 = 0.3) # Preliminaries W = G.W inds = GP.inds rs = GP.rs N = size(W, 1) jmax = size(rs, 2) fcols = size(G.f, 2) Uf = Matrix{Float64}(I, N, N) used_node = Set() dmatrixlH = zeros(N, jmax, fcols) dmatrixlHsym = deepcopy(dmatrixlH) for j = 1:jmax regioncount = count(!iszero, rs[:,j]) - 1 # assemble orthogonal folding operator at level j - 1 keep_folding!(Uf, used_node, W, GP; ϵ = ϵ, j = j - 1) for r = 1:regioncount # indices of current region indr = rs[r, j]:(rs[r + 1, j] - 1) # indices of current region's nodes indrs = inds[indr, j] # number of nodes in current region n = length(indrs) # compute the eigenvectors W_temp = W[indrs,indrs] D_temp = Diagonal(vec(sum(W_temp, dims = 1))) ## eigenvectors of L ==> svd(L) v = svd(Matrix(D_temp - W_temp)).U ## eigenvectors of L_sym ==> svd(L_sym) if minimum(sum(W[indrs, indrs], dims = 1)) > 10^3 * eps() ### eigenvectors of L_sym ==> svd(L_sym) D_temp_p = Diagonal(vec(sum(W_temp, dims = 1)).^(-0.5)) v_sym = svd(Matrix(D_temp_p * (D_temp - W_temp) * D_temp_p)).U else ### eigenvectors of L ==> svd(L) v_sym = deepcopy(v) end # standardize the eigenvector signs v = v[:,end:-1:1] standardize_eigenvector_signs!(v) v_sym = v_sym[:,end:-1:1] standardize_eigenvector_signs!(v_sym) # construct unfolding operator custom to current region P = Uf[indrs, :]' # obtain the expansion coefficients dmatrixlH[indr, j, :] = (P * v)' * G.f dmatrixlHsym[indr, j, :] = (P * v_sym)' * G.f end end return dmatrixlH, dmatrixlHsym end function standardize_eigenvector_signs!(v) # standardize the eigenvector signs for HGLET (different with NGWPs) for col = 1:size(v, 2) row = 1 standardized = false while !standardized if v[row, col] > 10^3 * eps() standardized = true elseif v[row,col] < -10^3 * eps() v[:, col] = -v[:, col] else row += 1 end end end end """ HGLET_dictionary(GP::GraphPart, G::GraphSig; gltype::Symbol = :L) assemble the whole HGLET dictionary ### Input Arguments * `GP`: a GraphPart object * `G`: a GraphSig object * `gltype`: `:L` or `:Lsym` ### Output Argument * `dictionary`: the HGLET dictionary """ function HGLET_dictionary(GP::GraphPart, G::GraphSig; gltype::Symbol = :L) N = size(G.W, 1) jmax = size(GP.rs, 2) dictionary = zeros(N, jmax, N) for j = 1:jmax BS = BasisSpec(collect(enumerate(j * ones(Int, N)))) dictionary[:, j, :] = HGLET_Synthesis(Matrix{Float64}(I, N, N), GP, BS, G; gltype = gltype)[1]' end return dictionary end """ LPHGLET_dictionary(GP::GraphPart, G::GraphSig; gltype::Symbol = :L, ϵ::Float64 = 0.3) assemble the whole LP-HGLET dictionary ### Input Arguments * `GP`: a GraphPart object * `G`: a GraphSig object * `gltype`: `:L` or `:Lsym` * `ϵ`: relative action bandwidth (default: 0.3) ### Output Argument * `dictionary`: the LP-HGLET dictionary """ function LPHGLET_dictionary(GP::GraphPart, G::GraphSig; gltype::Symbol = :L, ϵ::Float64 = 0.3) N = size(G.W, 1) jmax = size(GP.rs, 2) dictionary = zeros(N, jmax, N) for j = 1:jmax BS = BasisSpec(collect(enumerate(j * ones(Int, N)))) dictionary[:, j, :] = LPHGLET_Synthesis(Matrix{Float64}(I, N, N), GP, BS, G; gltype = gltype, ϵ = ϵ)[1]' end return dictionary end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
9445
function rising_cutoff(t) r = 0 if t <= -1 r = 0 elseif t >= 1 r = 1 else r = sin(π / 4 * (1 + sin(π / 2 * t))) end return r end function standardize_fiedler(v) v1 = deepcopy(v) v1 ./= norm(v1, 2) if v1[1] < 0 v1 = -v1 end return round.(v1; digits = 14) end function Lrw_eigenvec(W; nev = 6) # N = size(W, 1) # D = Diagonal(sum(W, dims = 1)[:]) # try # val, vtmp = eigs(D - W, D, # nev = nev, sigma = eps(), v0 = ones(N) / sqrt(N)) # vtmp = vtmp[:, sortperm(val)[2:end]] # vtmp ./= sqrt.(sum(vtmp.^2; dims = 1)) # vtmp *= Diagonal(1 .- (vtmp[1, :] .< 0) .* 2) # catch # # return round.(vtmp; digits = 14) deg = sum(W, dims = 1)[:] # weighted degree vector if minimum(deg) <= 10^3 * eps() L = Diagonal(deg) - W 𝛌, 𝚽 = eigen(Matrix(L)) standardize_eigenvector_signs!(𝚽) return round.(𝚽[:, 2:nev]; digits = 14) end Lsym = Diagonal(deg.^(-1/2)) * (Diagonal(deg) - W) * Diagonal(deg.^(-1/2)) 𝛌sym, 𝚽sym = eigen(Matrix(Lsym)) 𝚽rw = Diagonal(deg.^(-1/2)) * 𝚽sym 𝚽rw ./= sqrt.(sum(𝚽rw.^2; dims = 1)) 𝚽rw *= Diagonal(1 .- (𝚽rw[1, :] .< 0) .* 2) return round.(𝚽rw[:, 2:nev]; digits = 14) end function sortnodes_inmargin(active_region, Na, v, W, idx; sign = :positive) ind = sortperm(v[active_region]; rev = (sign == :positive)) # if there is a tie, use the more dims eigenmaps and sort by lexical order if length(unique(v[ind])) < length(active_region) emb = Lrw_eigenvec(W[idx, idx]; nev = 3)' # for the second dimension coordinate we sort # the pos region and the neg region in the same order emb_tp = [Tuple(emb[:, i] .* [1, (sign == :positive) * 2 - 1]) for i in 1:length(idx)] ind = sortperm(emb_tp[active_region]; rev = (sign == :positive)) end return ind[(end - Na + 1):end] end function find_pairinds(W; ϵ::Float64 = 0.2, idx = 1:size(W, 1), used_node = Set()) v = partition_fiedler(W[idx, idx])[2] v = standardize_fiedler(v) vmax = norm(v, Inf) N = length(v) pos_active_region = (Int64)[] neg_active_region = (Int64)[] tol = 10^3 * eps() tol *= ((sum(v .>= tol) > sum(v .<= -tol)) * 2 - 1) for i in 1:N if idx[i] ∈ used_node continue end if tol <= v[i] < ϵ * vmax push!(pos_active_region, i) end if -ϵ * vmax < v[i] < tol push!(neg_active_region, i) end end Np = length(pos_active_region) Nn = length(neg_active_region) Na = min(Nn, Np) # number of pair inds in action region # indp = sortperm(v[pos_active_region]; rev = true)[(end - Na + 1):end] # indn = sortperm(v[neg_active_region])[(end - Na + 1):end] indp = sortnodes_inmargin(pos_active_region, Na, v, W, idx; sign = :positive) indn = sortnodes_inmargin(neg_active_region, Na, v, W, idx; sign = :negative) pair_inds = vcat(idx[pos_active_region[indp]]', idx[neg_active_region[indn]]') return pair_inds, v end function pair_inds_shadding(W, GP; ϵ = 0.3, J = 1) rs = GP.rs inds = GP.inds (N, jmax) = Base.size(inds) used_node = Set() shading = zeros(N) for j = 1:J regioncount = count(!iszero, rs[:, j]) - 1 for r = 1:regioncount indr = rs[r, j]:(rs[r + 1, j] - 1) pair_inds = find_pairinds(W; ϵ = ϵ, idx = inds[indr, j], used_node = used_node)[1] for i in 1:size(pair_inds, 2) pv, nv = pair_inds[:, i] # if pv ∈ used_node || nv ∈ used_node # continue # end if shading[pv] == 0 shading[pv] = J + 3 - j end if shading[nv] == 0 shading[nv] = -(J + 3 - j) end end union!(used_node, Set(pair_inds[:])) end end return shading end function keep_folding!(U, used_node, W, GP; ϵ = 0.3, j = 1) if j == 0 return U end rs = GP.rs inds = GP.inds N = Base.size(inds, 1) regioncount = count(!iszero, rs[:, j]) - 1 for r = 1:regioncount indr = rs[r, j]:(rs[r + 1, j] - 1) if length(indr) == 1 continue end pair_inds, v = find_pairinds(W; ϵ = ϵ, idx = inds[indr, j], used_node = used_node) vmax = norm(v, Inf) for i in 1:size(pair_inds, 2) pv, nv = pair_inds[:, i] if pv ∈ used_node || nv ∈ used_node continue end # use the half distance between the 1D embeddings, # i.e., t = const⋅(v[pv] - v[nv] / 2), to compute the rising # cutoff function, which satisfy r(t)^2 + r(-t)^2 = 1 t = (v[findfirst(inds[indr, j] .== pv)] - v[findfirst(inds[indr, j] .== nv)]) / (2 * ϵ * vmax) # t = v[findfirst(inds[indr, j] .== pv)] / (ϵ * vmax) U[pv, pv] = rising_cutoff(t) U[pv, nv] = rising_cutoff(-t) U[nv, pv] = -rising_cutoff(-t) U[nv, nv] = rising_cutoff(t) end union!(used_node, Set(pair_inds[:])) end end function unitary_folding_operator(W, GP; ϵ = 0.3, J = 1) rs = GP.rs inds = GP.inds (N, jmax) = Base.size(inds) U = Matrix{Float64}(I, N, N) used_node = Set() for j = 1:J keep_folding!(U, used_node, W, GP; ϵ = ϵ, j = j) end return U end """ lp_ngwp(𝚽::Matrix{Float64}, W_dual::SparseMatrixCSC{Float64, Int64}, GP_dual::GraphPart; ϵ::Float64 = 0.3) construct the lapped NGWP and GP.tag in place. # Input Arguments - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors - `W_dual::SparseMatrixCSC{Float64, Int64}`: weight matrix of the dual graph - `GP_dual::GraphPart`: GraphPart object of the dual graph # Output Argument - `wavelet_packet::Array{Float64,3}`: the lapped NGWP dictionary. The first index is for selecting wavelets at a fixed level; the second index is for selecting the level `j`; the third index is for selecting elements in the wavelet vector. """ function lp_ngwp(𝚽::Matrix{Float64}, W_dual::SparseMatrixCSC{Float64, Int64}, GP_dual::GraphPart; ϵ::Float64 = 0.3) rs = GP_dual.rs inds = GP_dual.inds (N, jmax) = Base.size(inds) GP_dual.tag = zeros(Int, N, jmax) GP_dual.tag[:, 1] = Vector{Int}(0:(N - 1)) Uf = Matrix{Float64}(I, N, N) used_node = Set() wavelet_packet = zeros(N, jmax, N) wavelet_packet[:, 1, :] = Matrix{Float64}(I, N, N) for j = 2:jmax regioncount = count(!iszero, rs[:, j]) - 1 # Uf = unitary_folding_operator(W_dual, GP_dual; ϵ = ϵ, J = j - 1) keep_folding!(Uf, used_node, W_dual, GP_dual; ϵ = ϵ, j = j - 1) for r = 1:regioncount indr = rs[r, j]:(rs[r + 1, j] - 1) GP_dual.tag[indr, j] = Vector{Int}(0:(length(indr) - 1)) wavelet_packet[indr, j, :] = const_meyer_wavelets(𝚽, Uf; idx = inds[indr, j])' end end return wavelet_packet end function const_meyer_wavelets(𝚽, Uf; idx = 1:size(Uf, 1)) N = size(𝚽, 1) # 1. nice interpretable way by smooth orthogonal projector # assemble smooth orthogonal projector custom to nodes `idx` P = Uf[idx, :]' * Uf[idx, idx] if diag(P) == χ(idx, N) B = 𝚽[:, idx] else # folding the eigenspace, i.e., 𝚽's column space Y = 𝚽 * P # find its column space's orthogonal basis B = svd(Y).U end # 2. alternative faster way by orthogonal unfolding operator # B = 𝚽 * Uf[:, idx] # perform varimax rotation to get the meyer_wavelets Wavelets = varimax(B) return Wavelets end """ lp_ngwp_analysis(G::GraphSig, 𝚽::Matrix{Float64}, W_dual::SparseMatrixCSC{Float64, Int64}, GP_dual::GraphPart; ϵ::Float64 = 0.3) perform the LP-NGWP transform of the graph signal(s) `G.f`. # Input Arguments - `G::GraphSig`: a GraphSig object - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors - `W_dual::SparseMatrixCSC{Float64, Int64}`: weight matrix of the dual graph - `GP_dual::GraphPart`: GraphPart object of the dual graph # Output Argument - `wavelet_packet::Array{Float64,3}`: the lapped NGWP dictionary. The first index is for selecting wavelets at a fixed level; the second index is for selecting the level `j`; the third index is for selecting elements in the wavelet vector. """ function lp_ngwp_analysis(G::GraphSig, 𝚽::Matrix{Float64}, W_dual::SparseMatrixCSC{Float64, Int64}, GP_dual::GraphPart; ϵ::Float64 = 0.3) rs = GP_dual.rs inds = GP_dual.inds (N, jmax) = Base.size(inds) fcols = size(G.f, 2) GP_dual.tag = zeros(Int, N, jmax) GP_dual.tag[:, 1] = Vector{Int}(0:(N - 1)) Uf = Matrix{Float64}(I, N, N) used_node = Set() dmatrix = zeros(N, jmax, fcols) dmatrix[:, 1, :] = G.f for j = 2:jmax regioncount = count(!iszero, rs[:, j]) - 1 keep_folding!(Uf, used_node, W_dual, GP_dual; ϵ = ϵ, j = j - 1) for r = 1:regioncount indr = rs[r, j]:(rs[r + 1, j] - 1) GP_dual.tag[indr, j] = Vector{Int}(0:(length(indr) - 1)) dmatrix[indr, j, :] = const_meyer_wavelets(𝚽, Uf; idx = inds[indr, j])' * G.f end end return dmatrix end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
2293
__precompile__() module MultiscaleGraphSignalTransforms include("GraphSignal.jl") include("GraphPartition.jl") include("BasisSpecification.jl") include("common.jl") include("GHWT.jl") include("GHWT_2d.jl") include("GHWT_tf_1d.jl") include("GHWT_tf_2d.jl") include("HGLET.jl") include("GraphSig_Plot.jl") include("gplot.jl") include("partition_fiedler.jl") using Reexport @reexport using .GraphSignal, .GraphPartition, .BasisSpecification, .GHWT, .GHWT_2d, .GHWT_tf_1d, .GHWT_tf_2d, .HGLET export dvec2dmatrix, dmatrix2dvec, levlist2levlengths!, bsfull, bs_haar, bs_level, bs_walsh, dvec_Threshold, rs_to_region, GraphSig_Plot, gplot, gplot!, partition_fiedler export cost_functional, dmatrix_flatten, dmatrix_ldb_flatten ## export functions of NGWP.jl using LinearAlgebra, SparseArrays, Graphs, SimpleWeightedGraphs, Clustering using JuMP, Clp, Optim, Statistics, QuadGK, Arpack import Plots: plot, plot!, scatter, scatter! import StatsBase: crosscor include("dualgraph.jl") include("eigDAG_Distance.jl") include("eigHAD_Distance.jl") include("eigROT_Distance.jl") include("eigsROT_Distance.jl") include("eigTSD_Distance.jl") include("helpers.jl") include("LP-HGLET.jl") include("LP-NGWP.jl") include("natural_distances.jl") include("utils.jl") include("varimax.jl") include("NGWF.jl") include("NGWP.jl") include("PC-NGWP.jl") include("SunFlowerGraph.jl") include("VM-NGWP.jl") export eigDAG_Distance, eigHAD_Distance, eigHAD_Affinity export eigROT_Distance, ROT_Distance, eigEMD_Distance export eigsROT_Distance export eigTSD_Distance, K_functional export natural_eigdist export SunFlowerGraph, dualgraph export pc_ngwp, pairclustering, mgslp export vm_ngwp, varimax export lp_ngwp, rising_cutoff, find_pairinds, pair_inds_shadding, lp_ngwp_analysis export LPHGLET_Synthesis, LPHGLET_Analysis_All, HGLET_dictionary, LPHGLET_dictionary export unitary_folding_operator, keep_folding! export ngwp_analysis, ngwp_bestbasis, NGWP_jkl export natural_eigdist export nat_spec_filter, ngwf_all_vectors, rngwf_all_vectors, ngwf_vector, frame_approx, rngwf_lx export scatter_gplot, scatter_gplot!, stem, stem! export standardize_eigenvectors!, spike, characteristic, χ, sort_wavelets, transform2D export getall_expansioncoeffs, approx_error_plot, getall_expansioncoeffs2, approx_error_plot2 end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
3912
""" nat_spec_filter(l, D; σ = 0.25 * maximum(D), method = :regular, thres = 0.2) assemble the natural spectral graph filter centered at the l-th eigenvector via the distance matrix `D`. # Input Arguments - `l::Int64`: index of the centered eigenvector - `D::Matrix{Float64}`: non-trivial distance matrix of the eigenvectors - `σ::Float64`: Gaussian window width parameter (default: `0.25 * maximum(D)`) - `method::Symbol`: `:regular` or `:reduced` (default: `:regular`) - `thres::Float64`: cutoff threshold ∈ (0, 1). # Output Argument - `𝛍::Vector{Float64}`: the natural spectral graph filter """ function nat_spec_filter(l, D; σ = 0.25 * maximum(D), method = :regular, thres = 0.2) d = D[:, l] 𝛍 = exp.(-(d ./ σ).^2) 𝛍 ./= sum(𝛍) if method == :reduced 𝛍 .*= (𝛍 .> (thres * maximum(𝛍))) end return 𝛍 end """ ngwf_all_vectors(D, 𝚽; σ = 0.2 * maximum(D)) assemble the whole NGWF dictionary. # Input Arguments - `D::Matrix{Float64}`: non-trivial distance matrix of the eigenvectors - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors - `σ::Float64`: Gaussian window width parameter (default: `0.25 * maximum(D)`) # Output Argument - `𝓤::Matrix{Float64}`: the NGWF dictionary """ function ngwf_all_vectors(D, 𝚽; σ = 0.2 * maximum(D)) N = size(D, 1) 𝓤 = zeros(N, 0) for l = 1:N 𝛍 = nat_spec_filter(l, D; σ = σ) P = 𝚽 * Diagonal(𝛍) * 𝚽' 𝓤 = hcat(𝓤, P) end return 𝓤 end """ rngwf_all_vectors(D, 𝚽; σ = 0.2 * maximum(D), thres = 0.2) assemble the reduced NGWF (rNGWF) dictionary. # Input Arguments - `D::Matrix{Float64}`: non-trivial distance matrix of the eigenvectors - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors - `σ::Float64`: Gaussian window width parameter (default: `0.25 * maximum(D)`) - `thres::Float64`: cutoff threshold ∈ (0, 1). # Output Argument - `𝓤::Matrix{Float64}`: the rNGWF dictionary - `dic_l2x::Dict`: a dictionary to store the filtered locations by QR at the l-th centered eigenvector """ function rngwf_all_vectors(D, 𝚽; σ = 0.2 * maximum(D), thres = 0.2) N = size(D, 1) 𝓤 = zeros(N, 0) dic_l2x = Dict() for l = 1:N 𝛍 = nat_spec_filter(l, D; σ = σ, method = :reduced, thres = thres) P = 𝚽 * Diagonal(𝛍) * 𝚽' dic_l2x[l] = qr(P, Val(true)).p[1:rank(P, rtol = 10^4 * eps())] 𝓤 = hcat(𝓤, P[:, dic_l2x[l]]) end return 𝓤, dic_l2x end function ngwf_vector(D, l, x, 𝚽; σ = 0.1 * maximum(D)) N = size(𝚽, 1) P = 𝚽 * Diagonal(nat_spec_filter(l, D; σ = σ)) * 𝚽' ψ = P * spike(x, N) ψ ./= norm(ψ, 2) return ψ end """ frame_approx(f, U, V; num_kept = length(f)) approximate signal `f` by the frame `U`. # Input Arguments - `f::Vector{Float64}`: input graph signal - `U::Matrix{Float64}`: a frame operator (matrix or dictionary) - `V::Matrix{Float64}`: the dual frame operator of `U` - `num_kept::Int64`: number of kept coefficients (NCR) # Output Argument - `rel_error::Vector{Float64}`: the relative errors - `f_approx::Vector{Float64}`: the approximated signal """ function frame_approx(f, U, V; num_kept = length(f)) g = U' * f ind = sortperm(g.^2; rev = true)[1:num_kept] f_approx = zeros(length(f)) rel_error = [1.0] for γ in ind f_approx += g[γ] * V[:, γ] f_res = f - f_approx push!(rel_error, norm(f_res)/norm(f)) end return rel_error, f_approx end """ rngwf_lx(dic_l2x) find the sequential subindices of rNGWF vectors. # Input Arguments - `dic_l2x::Dict`: a dictionary to store the filtered locations by QR at the l-th centered eigenvector # Output Argument - `Γ::Vector{Tuple{Int64,Int64}}`: the sequential subindices of rNGWF vectors. """ function rngwf_lx(dic_l2x) N = length(dic_l2x) Γ = (Tuple{Int64,Int64})[] for l = 1:N for x in dic_l2x[l] push!(Γ, (l - 1, x)) end end return Γ end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
4970
""" ngwp_analysis(G::GraphSig, wavelet_packet::Array{Float64,3}) For a GraphSig object `G`, generate the matrix of NGWP expansion coefficients. # Input Arguments - `G::GraphSig`: an input GraphSig object - `wavelet_packet::Array{Float64,3}`: the varimax wavelets packet. # Output Argument - `dmatrix::Array{Float64,3}`: the expansion coefficients matrix. """ function ngwp_analysis(G::GraphSig, wavelet_packet::Array{Float64,3}) f = G.f fcols = size(f, 2) (N, jmax, ) = Base.size(wavelet_packet) dmatrix = zeros(N, jmax, fcols) dmatrix[:, 1, :] = f for j = 2:jmax for i = 1:N dmatrix[i, j, :] = f' * wavelet_packet[i, j, :] end end return dmatrix end """ const_proj_wavelets(𝚽,vlist,elist; method = "Modified Gram-Schmidt with Lp Pivoting") construct projection wavelets, i.e., project δ ∈ vlist onto span({φⱼ| j ∈ elist}). # Input Arguments - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors 𝚽 - `vlist::Array{Int}`: the list of considered node indices. - `elist::Array{Int}`: the list of considered eigenvector indices. - `method::Symbol`: default is `:MGSLp`. other options: `:IP` (Iterative-Projection), `GS` (Gram Schmidt). # Output Argument - `Wav::Matrix{Float64}`: a matrix whose columns are projected wavelet vectors. """ function const_proj_wavelets(𝚽, vlist, elist; method = :MGSLp) if length(vlist) == 1 return 𝚽[:, elist] end N = size(𝚽, 1) m = length(vlist) Wav = zeros(N, m) B = 𝚽[:, elist] if method == :IP for k in 1:length(vlist) wavelet = Proj(spike(vlist[k], N), B) Wav[:, k] .= wavelet ./ norm(wavelet) B = wavelet_perp_Matrix(wavelet, B) end elseif method == :GS P = B * B' for k in 1:length(vlist) wavelet = P * spike(vlist[k], N) Wav[:,k] .= wavelet ./ norm(wavelet) end Wav, complement_dim = gram_schmidt(Wav) if complement_dim != 0 complement_space = B * nullspace(Wav' * B) Wav = hcat(Wav, complement_space) end elseif method == :MGSLp P = B * B' for k in 1:length(vlist) wavelet = P * spike(vlist[k], N) Wav[:,k] .= wavelet ./ norm(wavelet) end Wav, complement_dim = mgslp(Wav) if complement_dim != 0 complement_space = B * nullspace(Wav' * B) Wav = hcat(Wav, complement_space) end else error("Do not support method ", method) end return Wav end """ function NGWP_jkl(GP_star::GraphPart, drow::Int, dcol::Int) Generate the (j,k,l) indices for the NGWP basis vector corresponding to the coefficient dmatrix(drow,dcol) ### Input Arguments * `GP_star::GraphPart`: a GraphPart object of the dual grpah * `drow::Int`: the row of the expansion coefficient * `dcol::Int`: the column of the expansion coefficient ### Output Argument * `j`: the level index of the expansion coefficient * `k`: the subregion in dual graph's index of the expansion coefficient * `l`: the tag of the expansion coefficient """ function NGWP_jkl(GP_star::GraphPart, drow::Int, dcol::Int) (j, k, l) = GHWT_jkl(GP_star, drow, dcol) return j,k,l end """ (dvec_ngwp, BS_ngwp) = ngwp_bestbasis(dmatrix::Array{Float64,3}, GP_star::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix, 2), useParent::Bool = true) Select the best basis from the matrix of NGWP expansion coefficients. # Input Arguments - `dmatrix::Array{Float64,3}`: the matrix of expansion coefficients - `GP_star::GraphPart`: an input GraphPart object of the dual graph - `cfspec::Any`: the specification of cost functional to be used (default = 1.0, i.e., 1-norm) - `flatten::Any`: the method for flattening vector-valued data to scalar-valued data (default = 1.0, i.e, 1-norm) - `useParent::Bool`: the flag to indicate if we update the selected best basis subspace to the parent when parent and child have the same cost (default = false) # Output Arguments - `dvec_ngwp::Matrix{Float64}`: the vector of expansion coefficients corresponding to the NGWP best basis - `BS_ngwp::BasisSpec`: a BasisSpec object which specifies the NGWP best basis """ function ngwp_bestbasis(dmatrix::Array{Float64,3}, GP_star::GraphPart; cfspec::Any = 1.0, flatten::Any = 1.0, j_start::Int = 1, j_end::Int = size(dmatrix, 2), useParent::Bool = false) dvec_ngwp, BS_ngwp = ghwt_c2f_bestbasis(dmatrix, GP_star; cfspec = cfspec, flatten = flatten, j_start = j_start, j_end = j_end, useParent = useParent) BS_ngwp.description = "NGWP Best Basis" return dvec_ngwp, BS_ngwp end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
4819
""" pairclustering(𝚽::Matrix{Float64}, GP_star::GraphPart) construct the GraphPart object of the primal graph via pair-clustering algorithm. # Input Arguments - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors 𝚽 - `GP_star::GraphPart`: GraphPart object of the dual graph # Output Argument - `GP::GraphPart`: GraphPart object of the primal graph via pair-clustering """ function pairclustering(𝚽::Matrix{Float64}, GP_star::GraphPart) rs_dual = GP_star.rs inds_dual = GP_star.inds (N, jmax) = Base.size(inds_dual) # TRACKING VARIABLES # `ind` records the way in which the nodes are indexed on each level ind = Vector{Int}(1:N) # `inds` records the way in which the nodes are indexed on all levels inds = zeros(Int, N, jmax) inds[:, 1] = ind # `rs` stands for regionstart, meaning that the index in `ind` of the first # point in region number `i` is `rs[i]` rs = deepcopy(rs_dual) j = 1 regioncount = 0 while regioncount < N regioncount = count(!iszero, rs[:, j]) - 1 if j == jmax # add a column to rs for level j+1, if necessary rs = hcat(rs, vcat(Int(1), zeros(Int, N))) inds = hcat(inds, zeros(Int, N)) jmax = jmax + 1 end # for tracking the child regions rr = 1 for r = 1:regioncount rs1 = rs[r, j] rs2 = rs[r + 1, j] n = rs2 - rs1 if n > 1 # regions with 2 or more nodes indrs = ind[rs1:(rs2 - 1)] n1 = rs[rr + 1, j + 1] - rs1 indrs_dual1 = inds_dual[rs1:(rs1 + n1 - 1), j + 1] indrs_dual2 = inds_dual[(rs1 + n1):(rs2 - 1), j + 1] # partition the current region (indp1, indp2) = partition_pc(𝚽, indrs, indrs_dual1, indrs_dual2) # update the indexing ind[rs1:(rs1 + n1 - 1)] = indrs[indp1] ind[(rs1 + n1):(rs2 - 1)] = indrs[indp2] # update the child region tracking rr += 2 elseif n == 1 rr += 1 end end j = j + 1 inds[:, j] = ind end # get rid of excess columns in rs rs = rs[:, 1:(j - 1)] # get rid of excess columns in inds inds = inds[:, 1:(j - 1)] return GraphPart(ind, rs; inds = inds) end """ partition_pc(𝚽::Matrix{Float64}, indrs::Vector{Int}, indrs_dual1::Vector{Int}, indrs_dual2::Vector{Int}) based on the partition on dual graph, partition the primal graph region (indexed by `indrs`) into two pieces via the pair-clustering algorithm. # Input Arguments - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors 𝚽 - `indrs::Vector{Int}`: indices of the primal graph region to be partitioned - `indrs_dual1::Vector{Int}`: index1 of the dual graph region's partition result - `indrs_dual2::Vector{Int}`: index2 of the dual graph region's partition result # Output Argument - `indp1::Vector{Int}`: index1 of `indrs` for the partition result - `indp2::Vector{Int}`: index2 of `indrs` for the partition result """ function partition_pc(𝚽::Matrix{Float64}, indrs::Vector{Int}, indrs_dual1::Vector{Int}, indrs_dual2::Vector{Int}) n = length(indrs) n1 = length(indrs_dual1) E = 𝚽[indrs, :].^2 score = sum(E[:, indrs_dual1], dims = 2) - sum(E[:, indrs_dual2], dims = 2) indp1 = sortperm(score[:]; rev = true)[1:n1] indp2 = setdiff(1:n, indp1) return indp1, indp2 end """ pc_ngwp(𝚽::Matrix{Float64}, GP_star::GraphPart, GP::GraphPart) construct pair-clustering NGWP and GP.tag in place. # Input Arguments - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors 𝚽 - `GP_star::GraphPart`: GraphPart object of the dual graph - `GP::GraphPart`: GraphPart object of the primal graph # Output Argument - `wavelet_packet::Array{Float64,3}`: the pair-clustering NGWP. The first index is for selecting wavelets at a fixed level; the second index is for selecting the level `j`; the third index is for selecting elements in the wavelet vector. """ function pc_ngwp(𝚽::Matrix{Float64}, GP_star::GraphPart, GP::GraphPart) rs = GP_star.rs inds_dual = GP_star.inds inds_primal = GP.inds (N, jmax) = Base.size(inds_dual) GP_star.tag = zeros(Int, N, jmax) GP_star.tag[:, 1] = Vector{Int}(0:(N - 1)) wavelet_packet = zeros(N, jmax, N) wavelet_packet[:, 1, :] = Matrix{Float64}(I, N, N) for j = 2:jmax regioncount = count(!iszero, rs[:, j]) - 1 for r = 1:regioncount indr = rs[r, j]:(rs[r + 1, j] - 1) GP_star.tag[indr, j] = Vector{Int}(0:(length(indr) - 1)) wavelet_packet[indr, j, :] = const_proj_wavelets(𝚽, inds_primal[indr, j], inds_dual[indr, j])' end end return wavelet_packet end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1346
using Graphs, SimpleWeightedGraphs, LinearAlgebra """ SunFlowerGraph(; N = 400) SUNFLOWERGRAPH construct a simple weighted sunflower graph with N vertices. Edge weights are the reciprocal of Euclidean distances. # Input Arguments - `N::Int64`: default is 400, the number of vertices. Requires N > 26. # Output Argument - `G::SimpleWeightedGraph{Int64,Float64}`: a simple weighted graph of the sunflower. - `L::Matrix{Float64}`: the weighted unnormalized graph Laplacian matrix. - `X::Matrix{Float64}`: a matrix whose i-th row represent the 2D coordinates of the i-th node. """ function SunFlowerGraph(; N = 400) c=1.0/N; θ=(sqrt(5.0)-1)*π; X = zeros(N,2); for k=1:N X[k,:]=c*(k-1)*[cos((k-1)*θ) sin((k-1)*θ)]; end G = SimpleWeightedGraph(N) for k = 2:8 G.weights[1,k] = 1/norm(X[1,:] - X[k,:]) G.weights[k,1] = 1/norm(X[1,:] - X[k,:]) end for k = 1:N if k+8 <= N G.weights[k,k+8] = 1/norm(X[k,:] - X[k+8,:]) G.weights[k+8,k] = 1/norm(X[k,:] - X[k+8,:]) end if k+13 <= N G.weights[k,k+13] = 1/norm(X[k,:] - X[k+13,:]) G.weights[k+13,k] = 1/norm(X[k,:] - X[k+13,:]) end end W = weights(G) #weighted adjacency_matrix Lw = Diagonal(sum(W, dims = 2)[:]) - W #weighted laplacian_matrix return G, Lw, X end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1154
""" vm_ngwp(𝚽::Matrix{Float64}, GP_star::GraphPart) construct varimax NGWP and GP_star.tag in place. # Input Arguments - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors 𝚽 - `GP_star::GraphPart`: GraphPart object of the dual graph # Output Argument - `wavelet_packet::Array{Float64,3}`: the varimax NGWP. The first index is for selecting wavelets at a fixed level; the second index is for selecting the level `j`; the third index is for selecting elements in the wavelet vector. """ function vm_ngwp(𝚽::Matrix{Float64}, GP_star::GraphPart) rs = GP_star.rs inds = GP_star.inds (N, jmax) = Base.size(inds) GP_star.tag = zeros(Int, N, jmax) GP_star.tag[:, 1] = Vector{Int}(0:(N - 1)) wavelet_packet = zeros(N, jmax, N) wavelet_packet[:, 1, :] = Matrix{Float64}(I, N, N) for j = 2:jmax regioncount = count(!iszero, rs[:, j]) - 1 for r = 1:regioncount indr = rs[r, j]:(rs[r + 1, j] - 1) GP_star.tag[indr, j] = Vector{Int}(0:(length(indr) - 1)) wavelet_packet[indr, j, :] = varimax(𝚽[:, inds[indr, j]])' end end return wavelet_packet end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
15347
using .GraphSignal, .GraphPartition, .BasisSpecification, LinearAlgebra """ dmatrix = dvec2dmatrix(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec) Given a vector of expansion coefficients, convert it to a matrix. ### Input Arguments * `dvec::Matrix{Float64}`: a vector of expansion coefficients * `GP::GraphPart`: a GraphPart object * `BS::BasisSpec`: a BasisSpec object ### Output Argument * `dmatrix::Array{Float64,3}`: a set of matrices of expansion coefficients """ function dvec2dmatrix(dvec::Matrix{Float64}, GP::GraphPart, BS::BasisSpec) # # 0. Preliminaries # # extract data # MATLAB: [levlist,levlengths] = ExtractData(BS,GP); #if isempty(BS.levlengths) && GP != nothing # levlist2levlengths!(GP, BS) #end levlist = BS.levlist #levlengths = BS.levlengths # constants (N, jmax) = Base.size(GP.rs) N = N - 1 fcols = Base.size(dvec, 2) # allocate space dmatrix = zeros(N, jmax, fcols) # # 1. Put the entries in the vector into the correct places in the matrix # # n = 1 # for row = 1:length(levlist) # dmatrix[n:(n + levlengths[row] - 1), levlist[row], :] = # dvec[n:(n + levlengths[row] - 1), :] # n += levlengths[row] # end for i = 1:length(levlist) dmatrix[levlist[i][1], levlist[i][2], :] = dvec[i,:] end # # 2. Return the `dmatrix` array # return dmatrix end # of function dvec2dmatrix """ (dvec, BS) = dmatrix2dvec(dmatrix::Array{Float64,3}, GP::GraphPart) Given a matrix of expansion coefficients, convert it to a vector. ### Input Arguments * `dmatrix::Array{Float64,3}`: matrices of expansion coefficients * `GP::GraphPart`: an input GraphPart object * `BS::BasisSpec`: an input BasisSpec object ### Outputs Arguments * `dvec::Matrix{Float64}`: a vector of expansion coefficients * `BS::BasisSpec`: an output BasisSpec object """ function dmatrix2dvec(dmatrix::Array{Float64,3}, GP::GraphPart) # constants (N, jmax, fcols) = Base.size(dmatrix) # THE BASIS IS NOT SPECIFIED ==> retain nonzero coeffs and specify the basis ## 0. Preliminaries # allocate/initialize dvec = dmatrix[:, jmax, :] levlist = jmax * ones(Int, N) ## 1. Make a vector of the nonzero basis entries for j = (jmax - 1):-1:1 regioncount = countnz(GP.rs[:, j]) - 1 for r = 1:regioncount indr = GP.rs[r, j]:(GP.rs[r + 1, j] - 1) if countnz(dmatrix[indr, j, :]) > 0 dvec[indr, :] = dmatrix[indr, j, :] levlist[GP.rs[r, j]:(GP.rs[r + 1, j] - 1)] .= j end end end ## 2. Specify the corresponding basis and return things levlist = collect(enumerate(levlist)) BS = BasisSpec(levlist) #levlist2levlengths!(GP, BS) return dvec, BS end # of function dmatrix2dvec (with no BS input) """ dvec = dmatrix2dvec(dmatrix::Array{Float64,3}, GP::GraphPart, BS::BasisSpec) Given a matrix of expansion coefficients, convert it to a vector. This function assumes that the input coefficient array `dmatrix` is in the coarse-to-fine format. If `BS.c2f == false`, then this function internally converts `dmatrix` into the fine-to-coarse format. Hence, if one supplies the f2c `dmatrix`, the results become wrong, and the subsequent procedure may result in error. ### Input Arguments * `dmatrix::Array{Float64,3}`: matrices of expansion coefficients * `GP::GraphPart`: an input GraphPart object * `BS::BasisSpec`: an input BasisSpec object ### Outputs Arguments * `dvec::Matrix{Float64}`: a vector of expansion coefficients """ function dmatrix2dvec(dmatrix::Array{Float64,3}, GP::GraphPart, BS::BasisSpec) # constants (N, jmax, fcols) = Base.size(dmatrix) # THE BASIS IS SPECIFIED ==> select the corresponding coefficients ## 0. Preliminaries # allocate space dvec = zeros(N, fcols) # if isempty(BS.levlengths) # levlist2levlengths!(GP, BS) # else # @warn("We assume that levlengths of the input BS were already computed properly prior to dmatrix2dvec.") # end levlist = BS.levlist #levlengths = BS.levlengths BSc2f = BS.c2f # put dmatrix in the fine-to-coarse arrangement, if necessary if !BSc2f # This assumes that dmatrix has not yet been arranged in f2c #if !BSc2f && isempty(GP.rsf2c) dmatrix = fine2coarse!(GP, dmatrix = dmatrix, coefp = true) end ## 1. Make a vector of the matrix entries specified by the BS object # n = 1 # for row = 1:length(levlist) # dvec[n:(n + levlengths[row] - 1), :] = # dmatrix[n:(n + levlengths[row] - 1), levlist[row], :] # n += levlengths[row] # end for i = 1:length(levlist) dvec[i,:] = dmatrix[levlist[i][1], levlist[i][2], :] end ## 2. Return the dvec return dvec end # of dmatrix2dvec (with BS input) """ levlist2levlengths!(GP::GraphPart, BS::BasisSpec) Compute the levlengths info for a BasisSpec object ### Input Arguments * `GP::GraphPart`: a GraphPart object * `BS::BasisSpec`: BasisSpec object, without `levlengths`; after this function, the `levlengths` field is filled. """ function levlist2levlengths!(GP::GraphPart, BS::BasisSpec) # 0. Preliminaries levlist = BS.levlist rs = GP.rs # allocate space levlengths = zeros(typeof(rs[1]), length(levlist)) # 1. Determine the length of each basis block specified by levlist if BS.c2f # coarse-to-fine case n = 0 for row = 1:length(levlist) # find the regionstart(s) of the next region # MATLAB: IX = find( GP.rs(:,levlist(row))==n+1, 1, 'last' ); IX = something(findlast(isequal(n+1), rs[:, levlist[row]]), 0) #IX = findlast( rs[:, levlist[row]], n + 1 ) levlengths[row] = rs[IX+1, levlist[row]] - rs[IX, levlist[row]] n += levlengths[row] end else # fine-to-coarse case n = 0 if isempty(GP.rsf2c) fine2coarse!(GP) end rsf2c = GP.rsf2c # This must be here: GP.rsf2c cannot be null! for row = 1:length(levlist) IX = something(findlast(isequal(n+1), rsf2c[:, levlist[row]]), 0) #IX = findlast( rsf2c[:, levlist[row]], n + 1 ) levlengths[row] = rsf2c[IX + 1, levlist[row]] - rsf2c[IX, levlist[row]] n += levlengths[row] end end # 2. Postprocessing # get rid of blocks with length 0 # MATLAB: levlist(levlengths == 0) = []; # levlengths(levlengths == 0) = []; # BS = BasisSpec(levlist,levlengths,c2f,description); levlist = levlist[levlengths .!= 0] # . before != is important here!! levlengths = levlengths[levlengths .!= 0] BS.levlengths = levlengths end # of function levlist2levlengths! """ (levlistfull, levlengthsfull, transfull) = bsfull(GP::GraphPart, BS::BasisSpec, trans::Vector{Bool}) Given a BasisSpec object, return the full-length, redundant levlist, levlengths, and trans descriptions. ### Input Arguments * `GP::GraphPart`: an input GraphPart object * `BS::BasisSpec`: an input BasisSpec object * `trans::Vector{Bool}`: a specification of the transforms used for the HGLET-GHWT hybrid transform (default: null) * `levlengthsp::Bool`: a flag to return levlengthsfull (default: false) * `transp::Bool`: a flag to return transfull (default: false) ### Output Arguments * `levlistfull::Vector{UInt8}`: the full-length, redundant levels list description * `levlengthsfull::Vector{UInt8}`: the full-length, redundant levels lengths description * `transfull::Matrix{Bool}`: the full-length, redundant trans description """ function bsfull(GP::GraphPart, BS::BasisSpec; trans::Vector{Bool} = Vector{Bool}(undef, 0), levlengthsp::Bool = false, transp::Bool = false) ## 0. Preliminaries # extract data if isempty(BS.levlengths) levlist2levlengths!(GP, BS) end levlist = BS.levlist levlengths = BS.levlengths # allocate space N = Base.length(GP.ind) levlistfull = zeros(Int, N) # Assuming that the maximum value of levlist <= jmax \approx log2(N) # can be representable by `UInt8`, i.e., N < \approx 5.79E76, which is # reasonable. We cannot handle such a large N at this point. if levlengthsp levlengthsfull = zeros(Int, N) end if transp && !isempty(trans) cols = Base.size(trans, 2) # MATLAB: transfull = false(N, cols) transfull = falses(N, cols) else transfull = falses(0) # transfull is empty. end ## 1. Fill out the redundant descriptions global idx = 0 for row = 1:length(levlist) levlistfull[(idx + 1):(idx + levlengths[row])] .= levlist[row] if levlengthsp levlengthsfull[(idx + 1):(idx + levlengths[row])] .= levlengths[row] end if !isempty(transfull) transfull[(idx + 1):(idx + levlengths[row]), :] = repmat(trans[row, :], levlengths[row], 1) end global idx += levlengths[row] end ## 2. Prepare the returns if levlengthsp if transp return levlistfull, levlengthsfull, transfull else return levlistfull, levlengthsfull end else if transp return levlistfull, transfull else return levlistfull end end end # of function bsfull """ BS = bs_haar(GP::GraphPart) Specify the Haar basis for a given graph partitioning ### Input Argument * `GP::GraphPart`: an input GraphPart object ### Output Argument * `BS::BasisSpec`: a BasisSpec object corresponding to the Haar basis """ # function bs_haar(GP::GraphPart) # # # determine jmax # jmax = Base.size(GP.rs, 2) # # # allocate space for levlist # levlist = zeros(Int, jmax) # # # fill in levlist for the Haar basis # levlist[1] = jmax # for row = 2:jmax # levlist[row] = jmax + 2 - row # end # # # make a BasisSpec object # BS = BasisSpec(levlist, c2f = false, description = "Haar basis") # # fill in the levlengths field of the BasisSpec object # levlist2levlengths!(GP, BS) # # return it # return BS # end # of function bs_haar function bs_haar(GP::GraphPart) if isempty(GP.tagf2c) fine2coarse!(GP) end # determine jmax jmax = Base.size(GP.rs, 2) # allocate space for levlist levlist = Vector{Tuple{Int,Int}}((findall(x->x==1, GP.tagf2c))) pushfirst!(levlist, (1, jmax)) # make a BasisSpec object BS = BasisSpec(levlist, c2f = false, description = "Haar basis") # fill in the levlengths field of the BasisSpec object #levlist2levlengths!(GP, BS) # return it return BS end # of function bs_haar """ BS = bs_level(GP::GraphPart, j::Int, c2f::Bool = true) Specify the basis corresponding to level j for a given graph partitioning ### Input Arguments * `GP::GraphPart`: an input GraphPart object * `j::Int`: the level to which the basis corresponds (`j = 0` is the global level) * `c2f::Bool`: a flag for c2f or f2c (default: true, i.e., c2f) ### Output Argument * `BS::BasisSpec`: a BasisSpec object corresponding to the level `j` basis """ function bs_level(GP::GraphPart, j::Int; c2f::Bool = true) # coarse-to-fine dictionary if c2f #rspointer = GP.rs[:, j + 1] bspec = "coarse-to-fine level $(j)" # fine-to-coarse dictionary else if isempty(GP.rsf2c) # if isempty(GP.tag) || isempty(GP.compinfo) # I don't think this part is necessary since GP should be partially filled. # ghwt_core!(GP) # end fine2coarse!(GP) end #rspointer = GP.rsf2c[:, j + 1] bspec = "fine-to-coarse level $(j)" end # specify the level j basis #Nj = countnz(rspointer) - 1 if isempty(GP.tag) # otherwise, it doesn't work for HGLET! N = size(GP.rs)[1]-1 else N = size(GP.tag, 1) end levlist = collect(enumerate((j + 1) * ones(Int,N))) BS = BasisSpec(levlist, c2f = c2f, description = bspec) # fill in the levlengths field of the BasisSpec object #levlist2levlengths!(GP, BS) # return it return BS end # of bs_level """ BS = bs_walsh(GP::GraphPart) Specify the walsh basis corresponding to for a given graph partitioning ### Input Arguments * `GP::GraphPart`: an input GraphPart object ### Output Argument * `BS::BasisSpec`: a BasisSpec object corresponding to the walsh basis """ function bs_walsh(GP::GraphPart) BS = bs_level(GP, 0, c2f = true) BS.description = "Walsh basis" return BS end # of bs_level """ function dvec_Threshold(dvec::Array{Float64}, SORH::String, keep::Float64, GP::GraphPart, BS::BasisSpec) Threshold HGLET / GHWT coefficients ### Input Arguments * `dvec::Array{Float64,2}` the vector of expansion coefficients * `SORH::String` use soft ('s') or hard ('h') thresholding * `keep::Float64` a fraction between 0 and 1 which says how many coefficients should be kept * `GP::GraphPart` a GraphPart object, used to identify scaling coefficients * `BS::BasisSpec` a BasisSpec object, used to identify scaling coefficients ### Output Argument * `dvec_new::Vector{Float64}` the thresholded expansion coefficients * `kept::Float64` the number of coefficients kept """ function dvec_Threshold(dvec::Array{Float64,2}, SORH::String, keep::Float64, GP::GraphPart, BS::BasisSpec) # # Apply to 1-D only for now. Need to modify in the future # dvec_new = deepcopy(dvec) # Obtain the number of coefficients kept if keep > 1 || keep < 0 error("The input keep should between 0~1") else kept = Int64(round(keep*size(dvec,1))) end if SORH == "s" || SORH == "soft" ind = sortperm(abs.(dvec[:]), rev = true) T = abs(dvec[ind[kept+1]]) if !isnothing(BS) #convert the tag matrix to a vector corresponding to BS tag = dmatrix2dvec(Array{Float64,3}(reshape(GP.tag,(size(GP.tag,1),size(GP.tag,2),1))),GP,BS) #soft-threshold the non-scaling coefficients ind = 1:size(dvec,1) ind = ind[(tag .> 0)[:]] dvec_new[ind] = sign.(dvec[ind]).*(abs.(dvec[ind]).-T).*(abs.(dvec[ind]).-T .>0) # if BS is not given, soft-threshold all coefficients else dvec_new = sign.(dvec).*(abs.(dvec).-T).*(abs.(dvec).-T.>0) end kept = count(!iszero, dvec_new) elseif SORH == "h" || SORH == "hard" ind = sortperm(abs.(dvec[:]), rev = true) dvec_new[ind[kept+1:end]] .= 0 kept = count(!iszero, dvec_new) else kept = count(!iszero, dvec_new) end return dvec_new, kept end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1178
""" dualgraph(dist::Matrix{Float64}; method::Symbol = :inverse, σ::Float64 = 1.0) build the dual graph's weight matrix based on the given non-trivial eigenvector metric. # Input Arguments - `dist::Matrix{Float64}`: eigenvector distance matrix - `method::Symbol`: default is by taking inverse of the distance between eigenvectors. Ways to build the dual graph edge weights. Option: `:inverse`, `:gaussian`. - `σ::Float64`: default is `1.0`. Gaussian variance parameter. # Output Argument - `G_star::GraphSig`: A `GraphSig` object containing the weight matrix of the dual graph. """ function dualgraph(dist::Matrix{Float64}; method::Symbol = :inverse, σ::Float64 = 1.0) N = Base.size(dist, 1) W_star = zeros(N, N) if method == :inverse for i = 1:(N - 1), j = (i + 1):N W_star[i, j] = 1 / dist[i, j] end elseif method == :gaussian for i = 1:(N - 1), j = (i + 1):N W_star[i, j] = exp(-dist[i, j] / σ^2) end else error("method must be :inverse or :gaussian.") end W_star = W_star + W_star' G_star = GraphSig(sparse(W_star); name = "dual graph") return G_star end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1372
""" eigDAG_Distance(𝚽, Q, numEigs; edge_weights = 1) compute DAG distances between pairwise graph Laplacian eigenvectors. # Input Arguments - `𝚽::Matrix{Float64}`: matrix of graph Laplacian eigenvectors, 𝜙ⱼ₋₁ (j = 1,...,size(𝚽,1)). - `Q::Matrix{Float64}`: incidence matrix of the graph. - `numEigs::Int64`: number of eigenvectors considered. - `edge_weight::Any`: default value is 1, stands for unweighted graph (i.e., all edge weights equal to 1). For weighted graph, edge_weight is the weights vector, which stores the affinity weight of each edge. # Output Argument - `dis::Matrix{Float64}`: a numEigs x numEigs distance matrix, dis[i,j] = d_DAG(𝜙ᵢ₋₁, 𝜙ⱼ₋₁). """ function eigDAG_Distance(𝚽, Q, numEigs; edge_weight = 1) dis = zeros(numEigs, numEigs) abs_∇𝚽 = abs.(Q' * 𝚽) for i = 1:numEigs, j = i+1:numEigs dis[i,j] = (edge_weight == 1) ? norm(abs_∇𝚽[:,i]-abs_∇𝚽[:,j],2) : norm((abs_∇𝚽[:,i]-abs_∇𝚽[:,j]).*sqrt.(edge_weight),2) end return dis + dis' end function eigDAG_Distance_normalized(𝚽,Q,numEigs; edge_weight = 1) dis = zeros(numEigs,numEigs) abs_∇𝚽 = abs.(Q' * 𝚽) for i = 1:numEigs, j = i+1:numEigs dis[i,j] = (edge_weight == 1) ? norm(abs_∇𝚽[:,i]-abs_∇𝚽[:,j],2) : norm((abs_∇𝚽[:,i]-abs_∇𝚽[:,j]).*sqrt.(edge_weight),2) dis[i,j] /= norm(𝚽[:,i] .* 𝚽[:,j],2) end return dis + dis' end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
2783
""" eigHAD_Distance(𝚽, 𝛌; indexEigs = 1:size(𝚽,2)) compute HAD "distance" (not really a distance) between pairwise graph Laplacian eigenvectors, i.e., d_HAD(𝜙ᵢ₋₁, 𝜙ⱼ₋₁) = √(1 - a_HAD(𝜙ᵢ₋₁, 𝜙ⱼ₋₁)²). # Input Arguments - `𝚽::Matrix{Float64}`: matrix of graph Laplacian eigenvectors, 𝜙ⱼ₋₁ (j = 1,...,size(𝚽,1)). - `𝛌::Array{Float64}`: array of eigenvalues. (ascending order) - `indexEigs::Int`: default is all eigenvectors, indices of eigenvectors considered. # Output Argument - `dis::Matrix{Float64}`: the HAD distance matrix, dis[i,j] = d_HAD(𝜙ᵢ₋₁, 𝜙ⱼ₋₁). """ function eigHAD_Distance(𝚽, 𝛌; indexEigs = 1:size(𝚽,2)) n = length(indexEigs) A = eigHAD_Affinity(𝚽, 𝛌; indexEigs = indexEigs) dis = sqrt.(ones(n, n) - A.^2) dis[diagind(dis)] .= 0 return dis end function eigHAD_Distance_neglog(𝚽, 𝛌; indexEigs = 1:size(𝚽,2)) A = eigHAD_Affinity(𝚽, 𝛌; indexEigs = indexEigs) n = size(A,1) dis = zeros(n,n) for i = 1:n, j = 1:n if A[i,j] == 0 dis[i,j] = 1e9 else dis[i,j] = -log(A[i,j]) end end return dis end """ eigHAD_Affinity(𝚽, 𝛌; indexEigs = 1:size(𝚽,2)) EIGHAD_AFFINITY compute Hadamard (HAD) affinity between pairwise graph Laplacian eigenvectors. # Input Arguments - `𝚽::Matrix{Float64}`: matrix of graph Laplacian eigenvectors, 𝜙ⱼ₋₁ (j = 1,...,size(𝚽,1)). - `𝛌::Array{Float64}`: array of eigenvalues. (ascending order) - `indexEigs::Int`: default is all eigenvectors, indices of eigenvectors considered. # Output Argument - `A::Matrix{Float64}`: a numEigs x numEigs affinity matrix, A[i,j] = a_HAD(𝜙ᵢ₋₁, 𝜙ⱼ₋₁). """ function eigHAD_Affinity(𝚽, 𝛌; indexEigs = 1:size(𝚽,2)) N, numEigs = size(𝚽,1), length(indexEigs) indNoDC = setdiff(indexEigs, 1) # get rid of DC component J = length(indNoDC) A = zeros(J, J) for a in 1:J, b in a:J i, j = indNoDC[a], indNoDC[b] hadamardProd = 𝚽[:,i] .* 𝚽[:,j] if norm(hadamardProd,2) < 0.01/sqrt(N) continue end λ, μ = 𝛌[i], 𝛌[j] x₀ = 1 ./ (max(λ, μ)) # Find minimizer t result = optimize(t -> abs(exp(-t[1]*λ) + exp(-t[1]*μ) - 1), [x₀], BFGS()); t = Optim.minimizer(result)[1] # Compute Hadamard affinity heatEvolution = 𝚽 * Diagonal(exp.(-t .* 𝛌)) * 𝚽' * hadamardProd A[a,b] = norm(heatEvolution,2) / (norm(hadamardProd,2) + 1e-6) end A = A + A'; for i in 1:J; A[i,i] /= 2; end if 1 in indexEigs # Set affinity measure of 𝜙₀ with itself to be the maximum and equals to 1. A = matrix_augmentation(A) A[1,1] = maximum(A) end return A ./ maximum(A) end function matrix_augmentation(A) m, n = size(A) B = zeros(m+1, n+1) B[2:end, 2:end] = A return B end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
3315
""" eigROT_Distance(P, Q; edge_length = 1, α = 1.0) computes the ROT distance matrix of P's column vectors on a graph. # Input Argument - `P::Matrix{Float64}`: a matrix whose columns are vector measures with the same total mass. - `Q::SparseMatrixCSC{Int64,Int64}`: the unweighted incidence matrix of the graph. - `edge_length::Any`: the length vector (default: 1 represents unweighted graphs) - `α::Float64`: default is 1.0. ROT parameter. # Output Argument - `dis::Matrix{Float64}`: distance matrix, dis[i,j] = d_{ROT}(pᵢ, pⱼ; α). """ function eigROT_Distance(P::Matrix{Float64}, Q::SparseMatrixCSC{Int64,Int64}; edge_length::Any = 1, α::Float64 = 1.0) n = size(P, 2) total_mass = sum(P, dims = 1)[:] if norm(total_mass - total_mass[1] * ones(n), Inf) > 10^4 * eps() @error("P's column measures do not share the same total mass.") return end dis = zeros(n,n) le2 = [edge_length; edge_length] Q2 = [Q -Q] m2 = size(Q2, 2) for i = 1:(n - 1), j = (i + 1):n f = P[:, i] - P[:, j] md = Model(optimizer_with_attributes(Clp.Optimizer, "LogLevel" => 0)) @variable(md, w[1:m2] >= 0.0) edge_length == 1 ? @objective(md, Min, sum(w)) : @objective(md, Min, sum(w .* le2)) @constraint(md, Q2 * w .== f) JuMP.optimize!(md) wt = abs.(JuMP.value.(w)) dis[i,j] = edge_length == 1 ? norm(wt.^α, 1) : norm((wt.^α) .* le2, 1) end return dis + dis' end """ ROT_Distance(A, B, Q; edge_length = 1, α = 1.0) computes the ROT distance matrix from A's column vectors to B's column vectors. If A, B are vector inputs, then it also returns the cost value and the optimal transport plan. # Input Argument - `A::Any`: a vector or matrix whose columns are initial probability measures. - `B::Any`: a vector or matrix whose columns are terminal probability measures. - `Q::SparseMatrixCSC{Int64,Int64}`: the unweighted incidence matrix of the graph. - `edge_length::Any`: the length vector (default: `1` represents unweighted graphs) - `α::Float64`: default is `1.0`. ROT parameter. - `retPlan::Bool`: an indicator if return the optimal plan (default: `false`) # Output Argument - `dis::Matrix{Float64}`: distance matrix, dis[i,j] = d_{ROT}(aᵢ, bⱼ; α). """ function ROT_Distance(A::Any, B::Any, Q::SparseMatrixCSC{Int64,Int64}; edge_length::Any = 1, α::Float64 = 1.0, retPlan::Bool = false) m = ndims(A) > 1 ? size(A, 2) : 1 n = ndims(B) > 1 ? size(B, 2) : 1 dis = zeros(m, n) le2 = [edge_length; edge_length] Q2 = [Q -Q] m2 = size(Q2, 2) for i = 1:m, j = 1:n f = (ndims(A) > 1 && ndims(B) > 1) ? B[:,j] - A[:,i] : B - A md = Model(optimizer_with_attributes(Clp.Optimizer, "LogLevel" => 0)) @variable(md, w[1:m2] >= 0.0) edge_length == 1 ? @objective(md, Min, sum(w)) : @objective(md, Min, sum(w .* le2)) @constraint(md, Q2 * w .== f) JuMP.optimize!(md) wt = abs.(JuMP.value.(w)) dis[i, j] = edge_length == 1 ? norm(wt.^α, 1) : norm((wt.^α) .* le2, 1) if ndims(A) == 1 && ndims(B) == 1 if retPlan return dis[1, 1], wt else return dis[1, 1] end end end return dis end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
3594
""" eigTSD_Distance(P::Matrix{Float64}, 𝚽::Matrix{Float64}, 𝛌::Vector{Float64}, Q::SparseMatrixCSC{Int64,Int64}; length::Any = 1, T::Any = :Inf, tol::Float64 = 1e-5) computes the TSD distance matrix of P's column vectors on a graph. # Input Argument - `P::Matrix{Float64}`: vector measures with the same total mass 0. - `𝚽::Matrix{Float64}`: matrix of the unweighted graph Laplacian eigenvectors. - `𝛌::Vector{Float64}`: vector of eigenvalues. - `Q::SparseMatrixCSC{Int64,Int64}`: the unweighted incidence matrix. - `length::Any`: vector of edge lengths (default: `1` represents unweighted graphs) - `T::Any`: the stopping time T in K_functional (default: `:Inf`) - `tol::Float64`: tolerance for integral convergence (default: `1e-5`) # Output Argument - `dis::Matrix{Float64}`: distance matrix, d_{TSD}(φᵢ, φⱼ; T). """ function eigTSD_Distance(P::Matrix{Float64}, 𝚽::Matrix{Float64}, 𝛌::Vector{Float64}, Q::SparseMatrixCSC{Int64,Int64}; length::Any = 1, T::Any = :Inf, tol::Float64 = 1e-5) N, ncols = Base.size(P) total_mass = sum(P, dims = 1)[:] if norm(total_mass - total_mass[1] * ones(ncols), Inf) > 10^4 * eps() @error("P's column measures do not share the same total mass.") return end # initialize the distance matrix dis = zeros(ncols, ncols) # store gradient of 𝚽 to avoid repeated computation ∇𝚽 = Q' * 𝚽 for i = 1:(ncols - 1), j = (i + 1):ncols dis[i, j] = K_functional(P[:, i], P[:, j], 𝚽, ∇𝚽, 𝛌; length = length, T = T, tol = tol)[1] end return dis + dis' end """ K_functional(𝐩::Vector{Float64}, 𝐪::Vector{Float64}, 𝚽::Matrix{Float64}, ∇𝚽::Matrix{Float64}, 𝛌::Vector{Float64}; length::Any = 1, T::Any = :Inf, dt::Float64 = 0.5/maximum(𝛌), tol::Float64 = 1e-5) computes the K_functional between two vector meassures 𝐩 and 𝐪 on a graph. # Input Argument - `𝐩::Vector{Float64}`: the source vector measure. - `𝐪::Vector{Float64}`: the destination vector measure. - `𝚽::Matrix{Float64}`: matrix of the unweighted graph Laplacian eigenvectors. - `∇𝚽::Matrix{Float64}`: gradient of unweighted graph Laplacian eigenvectors. - `𝛌::Vector{Float64}`: vector of eigenvalues. - `length::Any`: vector of edge lengths (default: 1 represents unweighted graphs) - `T::Any`: the stopping time T in K_functional (default: :Inf) - `tol::Float64`: tolerance for convergence (default: 1e-5) # Output Argument - `K::Float64`: TSD distance d_{TSD}(p, q; T). - `E::Float64`: an estimated upper bound on the absolute error. In general, `E <= tol * norm(K)`. """ function K_functional(𝐩::Vector{Float64}, 𝐪::Vector{Float64}, 𝚽::Matrix{Float64}, ∇𝚽::Matrix{Float64}, 𝛌::Vector{Float64}; length::Any = 1, T::Any = :Inf, tol::Float64 = 1e-5) if abs(sum(𝐩 - 𝐪)) > 10^4 * eps() @error("𝐩 and 𝐪 do not have the same total mass.") end f₀ = 𝐪 - 𝐩 # store b to avoid repeated computation b = 𝚽' * f₀ if T == :Inf # choose stopping time T such that exp(-λ₁T) = tol T = -log(tol) / 𝛌[2] end # use QuadGK.jl to numerically evaluate the integral K, E = quadgk(t -> weighted_1norm(∇f(t, ∇𝚽, b, 𝛌), length), 0, T, rtol=tol) return K, E end function ∇f(t, ∇𝚽, b, 𝛌) gu = ∇𝚽 * (exp.(-t * 𝛌) .* b) return gu end function weighted_1norm(x, length) if length == 1 return norm(x, 1) else return sum(abs.(x) .* length) end end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
3274
""" eigsROT_Distance(P::Matrix{Float64}, W::SparseMatrixCSC{Float64, Int64}, X::Matrix{Float64}; α::Float64 = 1.0) computes the sROT distance matrix of P's column vectors on a (unweighted) tree. # Input Argument - `P::Matrix{Float64}`: a matrix whose columns are vector measures with the same total mass. - `W::SparseMatrixCSC{Float64, Int64}`: the weight matrix of the tree. - `X::Matrix{Float64}`: the node positions (i-th row represents node `i`'s location) - `α::Float64`: default is 1.0. ROT parameter. # Output Argument - `dist_sROT::Matrix{Float64}`: distance matrix, dist_sROT[i,j] = d_{sROT}(pᵢ, pⱼ; α). - `Ws::SparseMatrixCSC{Float64, Int64}`: the weight matrix of the simplified tree. - `Xs::Matrix{Float64}`: the node locations of the simplified tree - `𝚯::Matrix{Float64}`: the shortened pmfs from `P`. """ function eigsROT_Distance(P::Matrix{Float64}, W::SparseMatrixCSC{Float64, Int64}, X::Matrix{Float64}; α::Float64 = 1.0) G = SimpleGraph(W) # check if the input weight matrix forms a tree if ne(G) + 1 != nv(G) || !is_connected(G) @error("input graph is not a tree.") end d = degree(G) # find index of junction nodes ijc = findall(d .> 2) # cut the graph into several disconnected subgraphs Wc = deepcopy(W) for i in ijc; Wc[i, :] .= 0; Wc[:, i] .= 0; end # find the indices for each subgraph Ind = find_subgraph_inds(Wc) # low dimensional pmfs 𝚯 = Ind' * P # the centroids of subgraphs Xs = Diagonal(1 ./ sum(Ind, dims = 1)[:]) * Ind' * X # build Gs, i.e., the graph of subgraphs or the simplified tree Gs = Graph(size(Ind, 2)) Ns = nv(Gs) # index of Gs's junction nodes ijcs = [] for k = 1:Ns supportind = findall(Ind[:, k] .== 1) if issubset(supportind, ijc) push!(ijcs, k) end end # connect the branches to the junctions to form the simplified tree for k in setdiff(1:Ns, ijcs) supportind = findall(Ind[:,k] .== 1) for i = 1:length(ijc) if sum(W[supportind, ijc[i]]) > 0 add_edge!(Gs, Edge(k, ijcs[i])) end end end Ws = 1.0 * adjacency_matrix(Gs) # compute the sROT distance matrix Qs = incidence_matrix(Gs; oriented = true) dist_sROT = eigROT_Distance(𝚯, Qs; edge_length = 1, α = α) return dist_sROT, Ws, Xs, 𝚯 end """ find_subgraph_inds(Wc::SparseMatrixCSC{Float64, Int64}) find all subgraph indices of a tree. (subgraph includes: branches and junctions) # Input Argument - `Wc::SparseMatrixCSC{Float64, Int64}`: the weight matrix of the tree chopped by the junctions. # Output Argument - `Ind::Matrix{Float64}`: a matrix whose columns represent the subgraph node indices in binary form. """ function find_subgraph_inds(Wc::SparseMatrixCSC{Float64, Int64}) N = size(Wc, 1) Dc = Diagonal(sum(Wc, dims=1)[:]) Lc = Matrix(Dc - Wc) 𝛌c, 𝚽c = eigen(Lc) p = findall(𝛌c .< 100 * eps()) Uc = 𝚽c[:, p] # use heat diffusion at t = ∞ and the siginal `1:N` to figure out all branch indices a = round.(1e8 * Uc * Uc' * [k for k = 1:N]) ind = unique(a) Ind = zeros(N, length(ind)) for k = 1:length(ind); Ind[findall(a .== ind[k]), k] .= 1; end return Ind end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
9108
using SparseArrays """ gplot(A, xyz; plotp = true, style = :auto, width = 2, color = :blue, shape = :none, mwidth = 2, mcolor = color, malpha = 1.0, mscolor = color, mswidth = 1, msalpha = 1.0, grid::Bool = false, label = "", subplot = 1) GPLOT Plot graph, as in graph theory. GPLOT(A,xyz,...) plots the graph specified by the adjacency matrix A and the node coordinates xyz. GPLOT!(A,xyz,...) adds a plot to `current` one. ### Input Arguments * `A::SparseMatrixCSC{Float64,Int}`: the adjacency matrix of a graph `G` * `xyz::Matrix{Float64}`: The coordinates array, `xyz`, is an n-by-2 or n-by-3 matrix with the position for node i in the i-th row, xyz[i,:] = [x[i] y[i]] or xyz[i,:] = [x[i] y[i] z[i]]. * `plotp::Bool`: if the plot is made (default) or return the X, Y, Z arrays * `style::Symbol`: of line; choose from Symbol\\[:auto,:solid,:dash,:dot,:dashdot\\] (default: :auto) * `width::Number`: of line in pixels (default: 2; fraction, e.g., 0.5 is allowed) * `color::Symbol`: of line; choose from Symbol\\[:white,:blue,:red,:green,...\\] (default: :blue) * `shape::Symbol`: choose from Symbol\\[:none,:auto,:circle,:rect,:star5,:diamond, :hexagon,:cross,:xcross,:utriangle, :dtriangle,:pentagon,:heptagon,:octagon, :star4,:star6,:star7,:star8,:vline,:hline\\] (default: :none) * `mwidth::Number`: marker size (or radius) in pixels (default: 2) * `mcolor::Symbol`: of marker (default: the same as line color) * `malpha::Float64`: opacity of marker interior; choose from \\[0,1\\] (default: 1.0) * `mswidth::Number`: marker stroke size (width) in pixels (default: 1) * `mscolor::Symbol`: of marker stroke (default: the same as line color) * `msalpha::Float64`: opacity of marker stroke; choose from \\[0,1\\] (default: 1.0) * `grid::Bool`: a flag to show grid lines (default: false) * `label::String`: a string for legend (default: "") * `subplot::Int`: subplot index (default: 1) ### Output Arguments * `X::Matrix{Float64}`: Nan-punctuated X coordinate vector * `Y::Matrix{Float64}`: Nan-punctuated Y coordinate vector * `Z::Matrix{Float64}`: Nan-punctuated Z coordinate vector (X,Y)= GPLOT(A,xyz,plotp=false,...) or (X,Y,Z) = GPLOT(A,xyz,plotp=false,...) return the NaN-punctuated vectors X and Y or X, Y and Z without actually generating a plot. These vectors can be used to generate the plot at a later time with PLOT or PLOT3D if desired. A backward-compatible elaboration of Mathworks's gplot that uses 3D data (if available) when the plot is rotated. Robert Piche, Tampere Univ. of Tech., 2005 Translated into julia by Naoki Saito, Dec. 21, 2016. Note that we should still consider the keywords organized as `function gplot(A,xyz,kw...)` Nicholas Hausch edits: Must install Plots package For 3D rotation, use `plotlyjs()` backend Revised by Naoki Saito, Feb. 17, 2017 Revised by Naoki Saito, Oct. 13, 2017 Revised by Haotian Li, Jul. 25, 2018 Revised by Haotian Li and Naoki Saito for Julia v0.7/1.0, Sep. 21, 2018 Instead of plot(...), we decided to use Plots.plot(...) in order to avoid the function name ambiguity; this is a safer approach. Revised by Naoki Saito, Oct. 22, 2018 """ function gplot(A::SparseMatrixCSC{Float64,Int}, xyz::Matrix{Float64}; plotp::Bool = true, style::Symbol = :auto, width::Number = 2, color::Symbol = :blue, shape::Symbol = :none, mwidth::Number = 1, mcolor::Symbol = color, malpha::Float64 = 1.0, mscolor::Symbol = color, mswidth::Number = 1, msalpha::Float64 = 1.0, grid::Bool = false, label::String = "", subplot::Int = 1) # If A is symmetric, then use only the upper triangular part for efficiency. if issymmetric(A) A = UpperTriangular(A) end # Extract the node indices ij = findall(A .!= 0.0); # Output of findall is an array of CartesianIndex. i = [ij[k][1] for k=1:length(ij)] j = [ij[k][2] for k=1:length(ij)] p = sortperm(max.(i,j)) i = i[p] j = j[p] # Find out whether the graph is 2-D or 3-D nspacedim = size(xyz, 2) if nspacedim == 1 xyz = hcat(xyz, zeros(size(xyz, 1))) nspacedim = 2 end # Create a long, NaN-separated list of line segments X = [ xyz[i,1] xyz[j,1] Base.fill(NaN,size(i)) ]' Y = [ xyz[i,2] xyz[j,2] Base.fill(NaN,size(i)) ]' X = X[:] Y = Y[:] if nspacedim == 3 Z = [ xyz[i,3] xyz[j,3] Base.fill(NaN,size(i)) ]' Z = Z[:] end # Finally, do the work! if plotp # plot the line-segments if nspacedim < 3 # 2D if shape == :none # no markers Plots.plot(X, Y, linestyle=style, linewidth=width, linecolor=color, grid=grid, label=label, subplot=subplot) else # marker attributes are set. Plots.plot(X, Y, linestyle=style, linewidth=width, linecolor=color, markershape=shape, markersize=mwidth, markercolor=mcolor, markeralpha=malpha, markerstrokecolor=mscolor, markerstrokewidth=mswidth, markerstrokealpha=msalpha, grid=grid, label=label, subplot=subplot) end else #3D if shape == :none # no markers Plots.plot(X, Y, Z, linestyle=style, linewidth=width, linecolor=color, grid=grid, label=label, subplot=subplot) else # marker attributes are set. Plots.plot(X, Y, Z, linestyle=style, linewidth=width, linecolor=color, markershape=shape, markersize=mwidth, markercolor=mcolor, markeralpha=malpha, markerstrokecolor=mscolor, markerstrokewidth=mswidth, markerstrokealpha=msalpha, grid=grid, label=label, subplot=subplot) end end else # Return the X, Y, Z array if desired. if nspacedim < 3 return X, Y else return X, Y, Z end end end function gplot!(A::SparseMatrixCSC{Float64,Int}, xyz::Matrix{Float64}; plotp::Bool = true, style::Symbol = :auto, width::Number = 2, color::Symbol = :blue, shape::Symbol = :none, mwidth::Number = 1, mcolor::Symbol = color, malpha::Float64 = 1.0, mscolor::Symbol = color, mswidth::Number = 1, msalpha::Float64 = 1.0, grid::Bool = false, label::String = "", subplot::Int = 1) # If A is symmetric, then use only the upper triangular part for efficiency. if issymmetric(A) A = UpperTriangular(A) end # Extract the node indices ij = findall(A .!= 0.0); # Output of findall is an array of CartesianIndex. i = [ij[k][1] for k=1:length(ij)] j = [ij[k][2] for k=1:length(ij)] p = sortperm(max.(i,j)) i = i[p] j = j[p] # Find out whether the graph is 2-D or 3-D nspacedim = size(xyz, 2) if nspacedim == 1 xyz = hcat(xyz, zeros(size(xyz, 1))) nspacedim = 2 end # Create a long, NaN-separated list of line segments X = [ xyz[i,1] xyz[j,1] Base.fill(NaN,size(i)) ]' Y = [ xyz[i,2] xyz[j,2] Base.fill(NaN,size(i)) ]' X = X[:] Y = Y[:] if nspacedim == 3 Z = [ xyz[i,3] xyz[j,3] Base.fill(NaN,size(i)) ]' Z = Z[:] end # Finally, do the work! if plotp # plot the line-segments if nspacedim < 3 # 2D if shape == :none # no markers Plots.plot!(X, Y, linestyle=style, linewidth=width, linecolor=color, grid=grid, label=label, subplot=subplot) else # marker attributes are set. Plots.plot!(X, Y, linestyle=style, linewidth=width, linecolor=color, markershape=shape, markersize=mwidth, markercolor=mcolor, markeralpha=malpha, markerstrokecolor=mscolor, markerstrokewidth=mswidth, markerstrokealpha=msalpha, grid=grid, label=label, subplot=subplot) end else #3D if shape == :none # no markers Plots.plot!(X, Y, Z, linestyle=style, linewidth=width, linecolor=color, grid=grid, label=label, subplot=subplot) else # marker attributes are set. Plots.plot!(X, Y, Z, linestyle=style, linewidth=width, linecolor=color, markershape=shape, markersize=mwidth, markercolor=mcolor, markeralpha=malpha, markerstrokecolor=mscolor, markerstrokewidth=mswidth, markerstrokealpha=msalpha, grid=grid, label=label, subplot=subplot) end end else # Return the X, Y, Z array if desired. if nspacedim < 3 return X, Y else return X, Y, Z end end end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
25085
""" findminimum(v, n) FINDMINIMUM finds the first n smallest elements' indices. # Input Arguments - `v::Array{Float64}`: the candidate values for selection. - `n::Int`: number of smallest elements for consideration. # Output Argument - `idx::Array{Int}`: n smallest elements' indices. """ function findminimum(v, n) idx = sortperm(v)[1:n] return idx end """ spike(i, N) SPIKE gives the N-dim spike vector with i-th element equals 1. # Input Arguments - `i::Int`: index for one. - `N::Int`: dimension of the target spike vector. # Output Argument - `v::Array{Float64}`: the N-dim spike vector with i-th element equals 1. """ function spike(i, N) v = zeros(N) v[i] = 1 return v end """ characteristic(list, N) CHARACTERISTIC gives the characteristic function in n-dim vector space with values of index in list equal to 1. # Input Arguments - `list::Array{Int}`: list of indices. - `N::Int`: dimension of the target vector. # Output Argument - `v::Array{Float64}`: the n-dim characteristic vector with values of index in list equal to 1. """ function characteristic(list, N) v = zeros(N) v[list] .= 1.0 return v end function χ(list, N) v = zeros(N) v[list] .= 1.0 return v end """ heat_sol(f0,𝚽,Σ,t) HEAT\\_SOL gives the solution of heat partial differential equation with initial condition u(⋅, 0) = f0 # Input Arguments - `f0::Array{Float64}`: initial condition vector. - `𝚽::Matrix{Float64}`: graph Laplacian eigenvectors, served as graph Fourier transform matrix - `Σ::Array{Int}`: diagonal matrix of eigenvalues. - `t::Float`: time elapse. # Output Argument - `u::Array{Float64}`: the solution vector at time t """ function heat_sol(f0, 𝚽, Σ, t) u = 𝚽 * (exp.(-t .* Σ) .* 𝚽' * f0) return u end """ freq_band_matrix(ls,n) FREQ\\_BAND\\_MATRIX provides characteristic diagonal matrix, which is useful for spectral graph filters design. # Input Arguments - `ls::Array{Int}`: list of indices. - `n::Int`: dimension of the target vector. # Output Argument - `D::Array{Float64}`: the zero/one diagonal matrix. """ function freq_band_matrix(ls, n) f = characteristic(list, n) return Diagonal(f) end """ scatter_gplot(X; marker = nothing, ms = 4, plotOrder = :normal, c = :viridis, subplot = 1) SCATTER\\_GPLOT generates a scatter plot figure, which is for quick viewing of a graph signal. SCATTER\\_GPLOT!(X; ...) adds a plot to `current` one. # Input Arguments - `X::Matrix{Float64}`: points locations, can be 2-dim or 3-dim. - `marker::Array{Float64}`: default is `nothing`. Present different colors given different signal value at each node. - `ms::Array{Float64}`: default is `4`. Present different node sizes given different signal value at each node. - `shape::Symbol`: default is `:none`. Shape of the markers. - `mswidth::Number`: default is `0`. Width of the marker stroke border. - `msalpha::Number`: default is `nothing`. The opacity for the marker stroke. - `plotOrder::Symbol`: default is `:normal`. Optional choices `:s2l` or `:l2s`, i.e., plots from the smallest value of `marker` to the largest value or the other way around, or `:propabs`, ms is automatically set to be proportional to the absolute value of the marker values. - `c::Symbol`: default is `:viridis`. Colors of the markers. - `subgplot::Int`: default is `1`. The subplot index. """ function scatter_gplot(X; marker = nothing, ms = 4, shape = :none, mswidth = 0, msalpha = nothing, plotOrder = :normal, c = :viridis, subplot = 1) N, dim = size(X) if !isnothing(marker) if size(marker) == (N,) || size(marker) == (N, 1) marker = marker[:] # reshape N x 1 matrix to a vector of length N else error("marker only accepts a vector of length $(N) or a matrix of size $(N) x 1.") end if plotOrder == :normal idx = 1:N elseif plotOrder == :s2l idx = sortperm(marker) elseif plotOrder == :l2s idx = sortperm(marker, rev = true) elseif plotOrder == :propabs idx = sortperm(abs.(marker)) else error("plotOrder only supports for :normal, :s2l, :l2s, or :propabs.") end X = X[idx, :] marker = marker[idx] if length(ms) > 1 ms = ms[idx] end # if plotOrder is :propabs, set ms to be a vector prop to # abs.(marker) automatically. # The maximum marker size is set to be maximum(ms). if plotOrder == :propabs maxmarkersize = maximum(ms) markerabsmax = maximum(abs.(marker)) ms = maxmarkersize .* log.(1 .+ abs.(marker)) ./ (log(1 + markerabsmax) + 10^3 * eps()) end end if dim == 2 scatter(X[:, 1], X[:, 2], marker_z = marker, ms = ms, shape = shape, c = c, legend = false, mswidth = mswidth, msalpha = msalpha, cbar = true, aspect_ratio = 1, grid = false, subplot = subplot) elseif dim == 3 scatter(X[:, 1], X[:, 2], X[:, 3], marker_z = marker, ms = ms, shape = shape, c = c, legend = false, mswidth = mswidth, msalpha = msalpha, cbar = true, aspect_ratio = 1, grid = false, subplot = subplot) else error("Dimension Error: scatter_gplot only supports for 2-dim or 3-dim scatter plots.") end end function scatter_gplot!(X; marker = nothing, ms = 4, shape = :none, mswidth = 0, msalpha = nothing, plotOrder = :normal, c = :viridis, subplot = 1) N, dim = size(X) if !isnothing(marker) if size(marker) == (N,) || size(marker) == (N, 1) marker = marker[:] # reshape N x 1 matrix to a vector of length N else error("marker only accepts a vector of length $(N) or a matrix of size $(N) x 1.") end if plotOrder == :normal idx = 1:N elseif plotOrder == :s2l idx = sortperm(marker) elseif plotOrder == :l2s idx = sortperm(marker, rev = true) elseif plotOrder == :propabs idx = sortperm(abs.(marker)) else error("plotOrder only supports for :normal, :s2l, :l2s, or :propabs.") end X = X[idx, :] marker = marker[idx] if length(ms) > 1 ms = ms[idx] end # if plotOrder is :propabs, set ms to be a vector prop to # abs.(marker) automatically # The maximum marker size is set to be maximum(ms). if plotOrder == :propabs maxmarkersize = maximum(ms) markerabsmax = maximum(abs.(marker)) ms = maxmarkersize .* log.(1 .+ abs.(marker)) ./ (log(1 + markerabsmax) + 10^3 * eps()) end end if dim == 2 scatter!(X[:, 1], X[:, 2], marker_z = marker, ms = ms, shape = shape, c = c, legend = false, mswidth = mswidth, msalpha = msalpha, cbar = true, aspect_ratio = 1, grid = false, subplot = subplot) elseif dim == 3 scatter!(X[:, 1], X[:, 2], X[:, 3], marker_z = marker, ms = ms, shape = shape, c = c, legend = false, mswidth = mswidth, msalpha = msalpha, cbar = true, aspect_ratio = 1, grid = false, subplot = subplot) else error("Dimension Error: scatter_gplot! only supports for 2-dim or 3-dim scatter plots.") end end """ cat_plot(X; marker = nothing, ms = 4) CAT\\_PLOT generates a scatter plot figure for cat example, which is for quick viewing of a graph signal within a specific range (i.e., xlims, ylims, zlims). CAT\\_PLOT!(X; ...) adds a plot to `current` one. # Input Arguments - `X::Matrix{Float64}`: 3-dim points. - `marker::Array{Float64}`: default is nothing. Present different colors given different signal value at each node. - `ms::Array{Float64}`: default is 4. Present different node sizes given different signal value at each node. """ function cat_plot(X; marker = nothing, ms = 4) scatter(X[:,1],X[:,2],X[:,3], marker_z = marker, ms = ms, c = :viridis, legend = false, cbar = true, aspect_ratio = 1, xlims = [-100, 100], ylims = [-100, 100], zlims = [-100, 100]) end function cat_plot!(X; marker = nothing, ms = 4) scatter!(X[:,1],X[:,2],X[:,3], marker_z = marker, ms = ms, c = :viridis, legend = false, cbar = true, aspect_ratio = 1, xlims = [-100, 100], ylims = [-100, 100], zlims = [-100, 100]) end """ approx_error_plot(DVEC::Vector{Vector{Float64}}; frac::Float64 = 0.50) draw relative approx. error w.r.t. fraction of coefficients retained (FCR) # Input Arguments - `DVEC::Vector{Vector{Float64}}`: a list of expansion coefficients. - `fraction::Float64`: default is 0.5. """ function approx_error_plot(DVEC::Vector{Vector{Float64}}; frac::Float64 = 0.50) plot(xaxis = "Fraction of Coefficients Retained", yaxis = "Relative Approximation Error") T = ["Laplacian", "HGLET", "Haar", "Walsh", "GHWT_c2f", "GHWT_f2c", "eGHWT", "PC-NGWP", "VM-NGWP"] L = [(:dashdot, :red), (:solid, :brown), (:dashdot, :orange), (:dashdot, :pink), (:solid, :gray), (:solid,:green), (:solid,:blue), (:solid,:purple), (:solid,:black)] for i = 1:length(DVEC) dvec = DVEC[i] N = length(dvec) dvec_norm = norm(dvec,2) dvec_sort = sort(dvec.^2) # the smallest first er = max.(sqrt.(reverse(cumsum(dvec_sort)))/dvec_norm, 1e-12) p = Int64(floor(frac*N)) + 1 # upper limit plot!(frac*(0:(p-1))/(p-1), er[1:p], yaxis=:log, xlims = (0.,frac), label = T[i], line = L[i], linewidth = 2, grid = false) end end """ getall_expansioncoeffs(G_Sig::GraphSig, GP_star::GraphPart, VM_NGWP::Array{Float64,3}, PC_NGWP::Array{Float64,3}, 𝚽::Matrix{Float64}) get all expansion coefficients of `f` via all methods in NGWP.jl and MTSG.jl # Input Arguments - `G_Sig::GraphSig`: GraphSig of the primal graph - `GP_star::GraphPart`: GraphPart of the dual graph - `VM_NGWP::Array{Float64,3}`: varimax NGWP. - `PC_NGWP::Array{Float64,3}`: pair-clustering NGWP. - `𝚽::Matrix{Float64}`: the matrix of graph Laplacian eigenvectors. """ function getall_expansioncoeffs(G_Sig::GraphSig, GP_star::GraphPart, VM_NGWP::Array{Float64,3}, PC_NGWP::Array{Float64,3}, 𝚽::Matrix{Float64}) ############# VM_NGWP dmatrix_VM = ngwp_analysis(G_Sig, VM_NGWP) dvec_vm_ngwp, BS_vm_ngwp = ngwp_bestbasis(dmatrix_VM, GP_star) ############# PC_NGWP dmatrix_PC = ngwp_analysis(G_Sig, PC_NGWP) dvec_pc_ngwp, BS_pc_ngwp = ngwp_bestbasis(dmatrix_PC, GP_star) ############# Laplacian dvec_Laplacian = 𝚽' * G_Sig.f ############# plain Laplacian eigenvectors coefficients GP = partition_tree_fiedler(G_Sig) dmatrixH = HGLET_Analysis_All(G_Sig, GP)[1] dvec_hglet, BS_hglet, _ = HGLET_GHWT_BestBasis(GP, dmatrixH = dmatrixH, cfspec = 1) dmatrix = ghwt_analysis!(G_Sig, GP = GP) ############# Haar BS_haar = bs_haar(GP) dvec_haar = dmatrix2dvec(dmatrix, GP, BS_haar) ############# Walsh BS_walsh = bs_walsh(GP) dvec_walsh = dmatrix2dvec(dmatrix, GP, BS_walsh) ############# GHWT_c2f dvec_c2f, BS_c2f = ghwt_c2f_bestbasis(dmatrix, GP) ############# GHWT_f2c dvec_f2c, BS_f2c = ghwt_f2c_bestbasis(dmatrix, GP) ############# eGHWT dvec_eghwt, BS_eghwt = ghwt_tf_bestbasis(dmatrix, GP) DVEC = [dvec_Laplacian[:], dvec_hglet[:], dvec_haar[:], dvec_walsh[:], dvec_c2f[:], dvec_f2c[:], dvec_eghwt[:], dvec_pc_ngwp[:], dvec_vm_ngwp[:]] return DVEC end using Clustering """ spectral_clustering(𝚽, M) SPECTRAL_CLUSTERING return M graph clusters, i.e., {Vₖ| k = 1,2,...,M}. # Input Argument - `𝚽::Matrix{Float64}`: the matrix of graph Laplacian eigenvectors. - `M::Int`: the number of graph clusters. # Output Argument - `clusters::Vector{Vector{Int}}`: graph cluster indices. """ function spectral_clustering(𝚽, M) if M < 2 return [1:size(𝚽, 1)] end cluster_indices = assignments(kmeans(𝚽[:, 2:M]', M)) clusters = Vector{Vector{Int}}[] for k in 1:M push!(clusters, findall(cluster_indices .== k)[:]) end return clusters end """ transform2D(X; s = 1, t = [0,0]) TRANSFORM2D dilate each point of `X` by scale s and translate by 2D vector t. """ function transform2D(X; s = 1, t = [0,0]) X1 = X .* s X2 = zeros(size(X)) for i in 1:size(X,1) X2[i,1] = X1[i,1] + t[1] X2[i,2] = X1[i,2] + t[2] end return X2 end """ NN_rendering(X, Img_Mat) NN\\_RENDERING generates a rendering signal at each point of `X` from the image `Img_Mat` by nearest neighbor method. """ function NN_rendering(X, Img_Mat) N = size(X,1) f = zeros(N) for i in 1:N nn_x, nn_y = Int(round(X[i, 2])), Int(round(X[i, 1])) if nn_x < 1 || nn_x > size(Img_Mat, 2) || nn_y < 1 || nn_y > size(Img_Mat, 1) print("Error: pixel out of boundary!") return end f[i] = Img_Mat[nn_x, nn_y] end return f end """ Bilinear_rendering(X, Img_Mat) NN\\_RENDERING generates a rendering signal at each point of `X` from the image `Img_Mat` by bilinear interpolation method. """ function Bilinear_rendering(X, Img_Mat) N = size(X,1) f = zeros(N) for i in 1:N x1, x2, y1, y2 = Int(floor(X[i, 2])), Int(floor(X[i, 2])) + 1, Int(floor(X[i, 1])), Int(floor(X[i, 1])) + 1 x, y = X[i,2], X[i,1] F = [Img_Mat[x1,y1] Img_Mat[x1,y2] Img_Mat[x2,y1] Img_Mat[x2,y2]] prod_res = 1/((x2 - x1) * (y2 - y1)) * [x2-x x-x1] * F * [y2-y y-y1]' f[i] = prod_res[1,1] end return f end """ dct1d(k, N) DCT1D returns k-th 1D DCT basis vector in Rᴺ. # Input Arguments - `k::Int64`: ord of DCT basis vector. k = 1,2,...,N. - `N::Int64`: vector dimension. # Output Argument - `φ::Array{Float64}`: k-th 1D DCT basis vector in Rᴺ. (k is 1-indexed) """ function dct1d(k, N) φ = [cos(π * (k - 1) * (l + 0.5) / N) for l = 0:(N - 1)] return φ ./ norm(φ, 2) end """ dct2d_basis(N1, N2) DCT2D\\_BASIS returns 2D DCT basis vectors in [0,1] x [0,1] with N1-1 and N2-1 subintervals respectively. # Input Arguments - `N1::Int64`: number of nodes in x-axis. - `N2::Int64`: number of nodes in y-axis. # Output Argument - `𝚽::Matrix{Float64}`: 2D DCT basis vectors. """ function dct2d_basis(N1, N2) N = N1 * N2 𝚽 = zeros(N, N) ind = 1 for i in 1:N1, j in 1:N2 φ₁, φ₂ = dct1d(i, N1), dct1d(j, N2) φ = reshape(φ₁ * φ₂', N) 𝚽[:, ind] = φ ind += 1 end return 𝚽 end """ alternating_numbers(n) ALTERNATING\\_NUMBERS e.g., n = 5, returns [1,5,2,4,3]; n = 6, returns [1,6,2,5,3,4] # Input Arguments - `n::Int64`: number of nodes in x-axis. # Output Argument - `arr::Array{Int64}`: result array. """ function alternating_numbers(n) mid = Int(ceil(n / 2)) arr1 = 1:mid arr2 = n:-1:(mid + 1) arr = Array{Int64}(zeros(n)) p1, p2 = 1, 1 for i = 1:n if i % 2 == 1 arr[i] = arr1[p1] p1 += 1 else arr[i] = arr2[p2] p2 += 1 end end return arr end """ compute_SNR(f, g) COMPUTE\\_SNR, g = f + ϵ, SNR = 20 * log10(norm(f)/norm(g-f)). # Input Arguments - `f::Array{Float64}`: original signal. - `g::Array{Float64}`: noisy signal. # Output Argument - `SNR::Float64`: SNR value. """ function compute_SNR(f, g) SNR = 20 * log10(norm(f) / norm(g - f)) return SNR end """ sort_wavelets(A; onlyByLoc = false) sort A's column wavelet vectors based on their focused nodes' indices. flip signs via the cross correlation. # Input Arguments - `A::Matrix{Float64}`: whose column vectors are wavelets. # Output Argument - `A::Matrix{Float64}`: a matrix with sorted and sign flipped column. """ function sort_wavelets(A; onlyByLoc = false) ord = findmax(abs.(A), dims = 1)[2][:] idx = sortperm([j[1] for j in ord]) A = A[:, idx] if onlyByLoc return A end N = size(A, 1) sgn = ones(size(A, 2)) mid = Int(round(size(A, 2) / 2)) A[:, mid] .*= (maximum(A[:, mid]) > -minimum(A[:, mid])) * 2 - 1 for i in 1:size(A, 2) cor_res = crosscor(A[:, mid], A[:, i], -Int(ceil(N / 2)):Int(floor(N / 2))) if maximum(cor_res) < -minimum(cor_res) sgn[i] = -1 end end A = A * Diagonal(sgn) return A end """ standardize_eigenvectors!(𝚽::Matrix{Float64}) standardize the signs of the eigenvectors such that 1) the term with the largest magnitude is positive; 2) if the max == -min, then make sure the first non-zero entry of the eigenvector is positive. # Input Arguments - `𝚽::Matrix{Float64}`: matrix of graph Laplacian eigenvectors """ function standardize_eigenvectors!(𝚽::Matrix{Float64}) N, nev = size(𝚽) tol = 10^3 * eps() for l in 1:nev 𝛟max = maximum(𝚽[:, l]) 𝛟min = minimum(𝚽[:, l]) if abs(𝛟max + 𝛟min) < tol row = 1 standardized = false while !standardized if 𝚽[row, l] > tol standardized = true elseif 𝚽[row, l] < -tol 𝚽[:, l] = -𝚽[:, l] else row += 1 end end elseif 𝛟max < -𝛟min 𝚽[:, l] *= -1 end end end """ getall_expansioncoeffs2(G_Sig::GraphSig, GP_star::GraphPart, GP_star_Lsym::GraphPart, VM_NGWP::Array{Float64,3}, PC_NGWP::Array{Float64,3}, LP_NGWP::Array{Float64,3}, VM_NGWP_Lsym::Array{Float64,3}, PC_NGWP_Lsym::Array{Float64,3}, LP_NGWP_Lsym::Array{Float64,3}, 𝚽::Matrix{Float64}, 𝚽sym::Matrix{Float64}) get all expansion coefficients of `f` in dissertation via all methods in NGWP.jl and MTSG.jl # Input Arguments - `G_Sig::GraphSig`: GraphSig of the primal graph - `GP_star::GraphPart`: GraphPart of the dual graph - `VM_NGWP::Array{Float64,3}`: varimax NGWP. - `PC_NGWP::Array{Float64,3}`: pair-clustering NGWP. - `LP_NGWP::Array{Float64,3}`: lapped NGWP. - `VM_NGWP_Lsym::Array{Float64,3}`: Lsym version of varimax NGWP. - `PC_NGWP_Lsym::Array{Float64,3}`: Lsym version of pair-clustering NGWP. - `LP_NGWP_Lsym::Array{Float64,3}`: Lsym version of lapped NGWP. - `𝚽::Matrix{Float64}`: the matrix of `L` eigenvectors. - `𝚽sym::Matrix{Float64}`: the matrix of `Lsym` eigenvectors. """ function getall_expansioncoeffs2(G_Sig::GraphSig, GP_star::GraphPart, GP_star_Lsym::GraphPart, VM_NGWP::Array{Float64,3}, PC_NGWP::Array{Float64,3}, LP_NGWP::Array{Float64,3}, VM_NGWP_Lsym::Array{Float64,3}, PC_NGWP_Lsym::Array{Float64,3}, LP_NGWP_Lsym::Array{Float64,3}, 𝚽::Matrix{Float64}, 𝚽sym::Matrix{Float64}) ############# VM_NGWP dmatrix_VM = ngwp_analysis(G_Sig, VM_NGWP) dvec_vm_ngwp, BS_vm_ngwp = ngwp_bestbasis(dmatrix_VM, GP_star) ############# PC_NGWP dmatrix_PC = ngwp_analysis(G_Sig, PC_NGWP) dvec_pc_ngwp, BS_pc_ngwp = ngwp_bestbasis(dmatrix_PC, GP_star) ############# LP_NGWP dmatrix_LP = ngwp_analysis(G_Sig, LP_NGWP) dvec_lp_ngwp, BS_lp_ngwp = ngwp_bestbasis(dmatrix_LP, GP_star) ############# VM_NGWP_Lsym dmatrix_VM_Lsym = ngwp_analysis(G_Sig, VM_NGWP_Lsym) dvec_vm_ngwp_Lsym, BS_vm_ngwp_Lsym = ngwp_bestbasis(dmatrix_VM_Lsym, GP_star_Lsym) ############# PC_NGWP_Lsym dmatrix_PC_Lsym = ngwp_analysis(G_Sig, PC_NGWP_Lsym) dvec_pc_ngwp_Lsym, BS_pc_ngwp_Lsym = ngwp_bestbasis(dmatrix_PC_Lsym, GP_star_Lsym) ############# LP_NGWP dmatrix_LP_Lsym = ngwp_analysis(G_Sig, LP_NGWP_Lsym) dvec_lp_ngwp_Lsym, BS_lp_ngwp_Lsym = ngwp_bestbasis(dmatrix_LP_Lsym, GP_star_Lsym) ############# Laplacian L dvec_Laplacian = 𝚽' * G_Sig.f ############# Laplacian Lsym dvec_Laplacian_sym = 𝚽sym' * G_Sig.f ############# HGLET GP = partition_tree_fiedler(G_Sig) dmatrixH, _, dmatrixHsym = HGLET_Analysis_All(G_Sig, GP) dvec_hglet, BS_hglet, trans_hglet = HGLET_GHWT_BestBasis(GP, dmatrixH = dmatrixH, dmatrixHsym = dmatrixHsym, cfspec = 1) ############# LP-HGLET dmatrixsH, dmatrixsHsym = LPHGLET_Analysis_All(G_Sig, GP; ϵ = 0.3) dvec_lphglet, BS_lphglet, trans_lphglet = HGLET_GHWT_BestBasis(GP, dmatrixH = dmatrixsH, dmatrixHsym = dmatrixsHsym, cfspec = 1) ############# GHWT dictionaries dmatrix = ghwt_analysis!(G_Sig, GP = GP) ############# Haar BS_haar = bs_haar(GP) dvec_haar = dmatrix2dvec(dmatrix, GP, BS_haar) ############# Walsh BS_walsh = bs_walsh(GP) dvec_walsh = dmatrix2dvec(dmatrix, GP, BS_walsh) ############# GHWT_c2f dvec_c2f, BS_c2f = ghwt_c2f_bestbasis(dmatrix, GP) ############# GHWT_f2c dvec_f2c, BS_f2c = ghwt_f2c_bestbasis(dmatrix, GP) ############# eGHWT dvec_eghwt, BS_eghwt = ghwt_tf_bestbasis(dmatrix, GP) DVEC = [dvec_Laplacian[:], dvec_Laplacian_sym[:], dvec_hglet[:], dvec_lphglet[:], dvec_haar[:], dvec_walsh[:], dvec_c2f[:], dvec_f2c[:], dvec_eghwt[:], dvec_pc_ngwp[:], dvec_pc_ngwp_Lsym[:], dvec_vm_ngwp[:], dvec_vm_ngwp_Lsym[:], dvec_lp_ngwp[:], dvec_lp_ngwp_Lsym[:]] return DVEC end """ approx_error_plot2(DVEC::Vector{Vector{Float64}}; frac::Float64 = 0.50) draw relative approx. error w.r.t. fraction of coefficients retained (FCR) in dissertation # Input Arguments - `DVEC::Vector{Vector{Float64}}`: a list of expansion coefficients. - `fraction::Float64`: default is 0.5. """ function approx_error_plot2(DVEC::Vector{Vector{Float64}}; frac::Float64 = 0.50) plot(xaxis = "Fraction of Coefficients Retained", yaxis = "Relative Approximation Error", size = (600, 500)) T = ["eigenbasis-L", "eigenbasis-Lsym", "HGLET", "LP-HGLET", "Haar", "Walsh", "GHWT_c2f", "GHWT_f2c", "eGHWT", "PC-NGWP", "PC-NGWP-Lsym", "VM-NGWP", "VM-NGWP-Lsym", "LP-NGWP", "LP-NGWP-Lsym"] L = [(:dot, :red), (:dot, :magenta), (:solid, :teal), (:dashdot, :teal), (:dashdot, :orange), (:dashdot, :pink), (:solid, :gray), (:solid, :green), (:solid, :blue), (:solid, :purple), (:dash, :purple), (:solid, :black), (:dash, :black), (:solid, :orange), (:dash, :orange)] for i = 1:length(DVEC) if i in [5, 6, 7, 8] continue end dvec = DVEC[i] N = length(dvec) dvec_norm = norm(dvec,2) dvec_sort = sort(dvec.^2) # the smallest first er = max.(sqrt.(reverse(cumsum(dvec_sort)))/dvec_norm, 1e-12) p = Int64(floor(frac*N)) + 1 # upper limit plot!(frac*(0:(p-1))/(p-1), er[1:p], yaxis=:log, xlims = (0.,frac), label = T[i], line = L[i], linewidth = 2, grid = false) end end """ stem(f; x = 1:length(f[:]), c = :black, ms = 5, shape = :circle, lw = 1) Display a length N discrete sequence data in a stem plot. # Input Arguments - `f`: function values could be a vector or an N x 1 matrix. - `x`: default is `1:N`. x values. - `c::Symbol`: default is `:black`. Color of the markers. - `ms::Number`: default is `5`. Size of markers. - `shape::Symbol`: default is `:circle`. Shape of the markers. - `lw::Number`: default is `1`. The line width of the stems. - `subgplot::Int`: default is `1`. The subplot index. """ function stem(f; x = 1:length(f[:]), c = :black, ms = 5, shape = :circle, lw = 1, subplot = 1) if (ndims(f) == 2 && size(f, 2) > 1) || ndims(f) > 2 error("input only accepts a vector or a matrix of size (N, 1).") return end f = f[:] N = length(f) plot(x, f, seriestype = :stem, color = c, lw = lw, subplot = subplot) scatter!(x, f, marker = shape, color = c, ms = ms, mswidth = 0, subplot = subplot) plot!(x, zeros(N), color = :black, lw = lw, subplot = subplot) plot!(grid = false, legend = false, ratio = 1, frame = :none, subplot = subplot) end function stem!(f; x = 1:length(f[:]), c = :black, ms = 5, shape = :circle, lw = 1, subplot = 1) if (ndims(f) == 2 && size(f, 2) > 1) || ndims(f) > 2 error("input only accepts a vector or a matrix of size (N, 1).") return end f = f[:] N = length(f) plot!(x, f, seriestype = :stem, color = c, lw = lw, subplot = subplot) scatter!(x, f, marker = shape, color = c, ms = ms, mswidth = 0, subplot = subplot) plot!(x, zeros(N), color = :black, lw = lw, subplot = subplot) plot!(grid = false, legend = false, ratio = 1, frame = :none, subplot = subplot) end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
2101
""" natural_eigdist(𝚽, 𝛌, Q; α = 1.0, T = :Inf, input_format = :zero_measures, distance = :DAG, edge_weight = 1, edge_length = 1) compute natural distances between graph Laplacian eigenvectors. # Input Arguments - `𝚽::Matrix{Float64}`: matrix of (weighted) graph Laplacian eigenvectors. - `𝛌::Vector{Float64}`: vector of eigenvalues. - `Q::Matrix{Float64}`: unweighted incidence matrix of the graph. - `α::Float64`: ROT parameter. (default: `1.0`) - `T::Any`: TSD parameter, i.e., the stopping time T in K_functional (default: `:Inf`) - `input_format::Symbol`: options: `:zero_measures`, `:pmf1` and `:pmf2` (default: `:zero_measures`) - `distance::Symbol`: options: `:ROT`, `:HAD`, `:DAG` and `:TSD` (default: `:DAG`) - `edg_length::Any`: vector of edge lengths (default: 1 represents unweighted graphs) - `edge_weight::Any`: the weights vector, which stores the affinity weight of each edge (default: `1` represents unweighted graphs). # Output Argument - `dis::Matrix{Float64}`: the distance matrix, dis[i,j] = d(𝜙ᵢ₋₁, 𝜙ⱼ₋₁). """ function natural_eigdist(𝚽, 𝛌, Q; α = 1.0, T = :Inf, input_format = :zero_measures, distance = :DAG, edge_weight = 1, edge_length = 1) N = size(Q, 1) P = deepcopy(𝚽) if input_format == :zero_measures P[:, 1] .= 0 elseif input_format == :pmf1 P = P.^2 elseif input_format == :pmf2 P = exp.(P) ./ sum(exp.(P), dims = 1) else @error("input_format does not support $(input_format)!") return end if distance == :ROT D = eigROT_Distance(P, Q; edge_length = edge_length, α = α) elseif distance == :HAD D = eigHAD_Distance(𝚽, 𝛌) elseif distance == :DAG D = eigDAG_Distance(𝚽, Q, N; edge_weight = edge_weight) elseif distance == :TSD tL = Q * Q' t𝛌, t𝚽 = eigen(Matrix(tL)) D = eigTSD_Distance(P, t𝚽, t𝛌, Q; length = edge_length, T = T) else error("distance does not support $(distance)!") return end return D end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
11642
using SparseArrays using Statistics using LinearAlgebra using Arpack """ (pm,v) = partition_fiedler(W; method, v) Partition the vertices of a graph according to the Fiedler vector ### Input Arguments * `W::SparseMatrixCSC{Float64,Int}`: the edge weight matrix * `method::Symbol`: the parition method to be used (:L or :Lrw or else ...) * `v::Vector{Float64}`: the Fiedler vector supplied if `v` is a null vector ### Output Arguments * `pm::Vector{Int}`: a vector of 1's and -1's * `v::Vector{Float64}`: the Fiedler vector used for graph partitioning Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) Translated and revised by Naoki Saito, Feb. 9, 2017 """ function partition_fiedler(W::SparseMatrixCSC{Float64,Int}; method::Symbol = :Lrw, v::Vector{Float64} =Vector{Float64}(undef, 0)) # # Easy case: the Fiedler vector is provided # if !isempty(v) (pm, v) = partition_fiedler_pm(v) if size(W, 1) == length(v) # recovering the algebraic connectivity a(G) # Note: regardless of v coming from L or Lrw, the eigenvalue # computation below is fine: v'*L*v = a(G) or arw(G) because # for L: v'*L*v = \lambda v'*v = \lambda # for Lrw: vrw'*L*vrw = \lambda vrw'*D*vrw = \lambda # Note also, the result of the quadratic form is scalar # mathematically, but in julia, it's 1x1 array; so need to # convert it to a real scalar via `val = val[1]`. val = v' * (Diagonal(vec(sum(W, dims = 1))) - W) * v; val = val[1] pm = partition_fiedler_troubleshooting(pm, v, W, val) else pm = partition_fiedler_troubleshooting(pm) end return pm, v end # # Now, we need to compute the Fiedler vector here. Preliminaries first. # N = size(W, 1) eigs_flag = 0 sigma = eps() cutoff = 128 # this value could be changed... # handle the case when there are 2 nodes if N == 2 pm = [1; -1] v = pm / sqrt(2) return pm, v end # Use L (unnormalized) if specified or edge weights are very small if method == :L || minimum(sum(W, dims = 1)) < 10^3 * sigma if N > cutoff # for a relative large W v0 = ones(N) / sqrt(N) try # MATLAB, [v,val,eigs_flag] = eigs(diag(sum(W))-W,2,sigma,opts); val, vtmp = eigs(sparse(Diagonal(vec(sum(W, dims = 1)))) - W, nev = 2, sigma = sigma, v0 = v0) # val = real.(val) # vtmp = real.(vtmp) if isa(val[1], Complex{Float64}) eigs_flag = 1 end catch emsg @warn("Exception in eigs(L) occurred: ", emsg) eigs_flag = 2 end if eigs_flag == 0 # no problem in `eigs` is detected. val, ind = findmax(val) # val is set to be a scalar. v = vec(vtmp[:, ind]) # This is the Fiedler vector! # In MATLAB, val was returned as a diagonal matrix, so we had to # do all these manipulations while julia, val is simply a vector. # [~,ind] = max(diag(val)); # v = v(:,ind); # val = val(ind,ind); end end if N <= cutoff || eigs_flag != 0 # if W is small or eigs had a problem, # then use full svd. vtmp, val = svd(Matrix(Diagonal(vec(sum(W, dims = 1))) - W)) # v <-> U, val <-> S # Diagonal(vec(sum(W,1))) is Matrix{Float64} while W is SparseMatrix # But the results of the subtraction becomes Matrix{Float64}. # Also be careful here! val[end-2] == val[end-1] can happen. # If that is the case, vtmp[:,end-2] could also be the Fiedler vec. v = vec(vtmp[:, end - 1]) # v is set to be a vector. val = val[end - 1] # val is set to a scalar. # In MATLAB, `full` was necessary to convert a sparse matrix format # to a usual matrix format as follows # [v,val,~] = svd(full(diag(sum(W))-W)); end elseif method == :Lrw # Otherwise, use L_rw, which is normally preferred. if N > cutoff # for a relatively large W v0 = ones(N) / sqrt(N) try # MATLAB: [v,val,eigs_flag] = ... # eigs(diag(sum(W))-W,diag(sum(W)),2,sigma,opts); # This is L*v = \lambda*D*v case. temp = sparse(Diagonal(vec(sum(W, dims = 1)))) val, vtmp = eigs(temp - W, temp, nev = 2, sigma = sigma, v0 = v0) # val = real.(val) # vtmp = real.(vtmp) if isa(val[1], Complex{Float64}) eigs_flag = 1 end catch emsg @warn("Exception in eigs(Lrw) occurred: ", emsg) eigs_flag = 2 end if eigs_flag == 0 val, ind = findmax(val) # val is set to be a scalar. v = vtmp[:, ind] # MATLAB: v = (full(sum(W,2)).^(-0.5)) .* v # v = vec((sum(W, dims = 2).^(-0.5)) .* v) # This is the Fiedler vector! end end if N <= cutoff || eigs_flag != 0 # if W is small or eigs had a problem, # then use full svd colsumW = vec(sum(W, dims = 1)) D = Diagonal(colsumW) D2 = Diagonal(colsumW.^(-0.5)) vtmp, val = svd(Matrix(D2 * (D - W) * D2)) # SVD of Lsym # MATLAB: [v,val,~] = svd(full(... # bsxfun(@times,bsxfun(@times,full(sum(W,2)).^(-0.5),diag(sum(W))-W), # full(sum(W,1)).^(-0.5)) ) ); # # SVD is ordered in the order of nonincreasing singular values, # so, (end-1) entry corresponds to the algebraic connectivity. # Also be careful here! val[end-2] == val[end-1] can happen. # If that is the case, vtmp[:,end-2] could also be the Fiedler vec. val = val[end - 1] # val is set to be a scalar. v = vtmp[:, end - 1] # v is set to be a vector. v = vec((sum(W, dims = 2).^(-0.5)) .* v) # This is the Fiedler vector of Lrw! end else # Unknown method is specified. error("Graph partitioning method :", method, " is not recognized!") end # partition using the Fiedler vector and troubleshoot any potential issues pm, v = partition_fiedler_pm(v) pm = partition_fiedler_troubleshooting(pm, v, W, val) return pm, v end # of partition_fiedler """ (pm, v) = partition_fiedler_pm(v::Vector{Float64}) Partition an input Graph based on the Fiedler vector `v` ### Input Argument * `v::Vector{Float64}`: the input Fiedler vector ### Output Arguments * `pm::Vector{Int}`: the partition info * `v::Vector{Float64}`: the output Fiedler vector if requested Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) Translated and revised by Naoki Saito, Feb. 10, 2017 """ function partition_fiedler_pm(v::Vector{Float64}) # define a tolerance: if abs(x) < tol, then we view x = 0. tol = 10^3 * eps() # set the first nonzero element to be positive row = 1 while abs(v[row]) < tol && row < length(v) row += 1 end if v[row] < 0 v = -v end # assign each point to either region 1 or region -1, and assign any zero # entries to the smaller region if sum(v .>= tol) > sum(v .<= -tol) # more (+) than (-) entries pm = 2*(v .>= tol) .- 1 else pm = 2*(v .<= -tol) .- 1 end # make sure the first point is assigned to region 1 (not -1) if pm[1] < 0 pm = -pm end return pm, v end # of partition_fiedler_pm """ pm = partition_fiedler_troubleshooting(pm,v,W,val) Troubleshoot potential issues with the partitioning ### Input Arguments * `pm::Vector{Int}`: an input partition info (+1 or -1) of each node * `v::Vector{Float64}`: the Fiedler vector of the graph * `W::SparseMatrixCSC{Float64,Int}`: an input edge weight matrix * `val::Float64`: the algebraic connectivity (i.e., ``\\lambda_2``) ### Ouput Arguments * `pm::Vector{Int}`: a final partition info vector Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) Translated and revised by Naoki Saito, Feb. 10, 2017 """ function partition_fiedler_troubleshooting(pm::Vector{Int},v::Vector{Float64}, W::SparseMatrixCSC{Float64,Int}, val::Float64) # Initial setup N = length(pm) tol = 10^3 * eps() # If pm vector indicates no partition (single sign) or ambiguities via # 0 entries, then we'll trouble shoot. if sum(pm .< 0) == 0 || sum(pm .> 0) == 0 || sum(abs.(pm)) < N # Case 1: an input graph is not connected (i.e., alg. conn < tol) if val < tol pm = 2 .* (abs.(v) .> tol) .- 1 while sum(pm .< 0) == 0 || sum(pm .> 0) == 0 tol = 10 * tol # relax the tolerance pm = 2 .* (abs.(v) .> tol) .- 1 if tol > 1 pm[1:Int(ceil(N / 2))] .= 1 pm[(Int(ceil(N / 2)) + 1):N] .= -1 end end # Case 2: it is connected, but something funny happened else pm = 2 .* (v .>= mean(v)) .- 1 if sum(abs.(pm)) < N # assign the near-zero points based on the values of v # at their neighbor nodes pm0 = find(pm .== 0) pm[pm0] = (W[pm0, :] * v .> tol) - (W[pm0, :] * v .< -tol) # assign any remaining zeros to the group with fewer members pm[find(pm .== 0)] = (sum(pm .> 0) - sum(pm .< 0)) .>= 0 end end # if one region has no points after all the above processing if sum(pm .< 0) == 0 || sum(pm .> 0) == 0 pm[1:Int(ceil(N / 2))] .= 1 pm[Int(ceil(N / 2) + 1):N] .= -1 end end # make sure that the first point is assigned as a 1 if pm[1] < 0 pm = -pm end return pm end # of partition_fiedler_troubleshooting """ pm = partition_fiedler_troubleshooting(pm) Troubleshoot potential issues with the partitioning ### Input Arguments * `pm::Vector{Int}`: an input partition info (+1 or -1) of each node ### Ouput Arguments * `pm::Vector{Int}`: a final partition info vector Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) Translated and revised by Naoki Saito, Feb. 10, 2017 """ function partition_fiedler_troubleshooting(pm::Vector{Int}) N = length(pm) if sum(pm .< 0) == 0 || sum(pm .> 0) == 0 pm[1:Int(ceil(N / 2))] = 1 pm[Int(ceil(N / 2) + 1):N] = -1 end # make sure that the first point is assigned as a 1 if pm[1] < 0 pm = -pm end return pm end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
7575
""" rse = PartitionTreeMatrix_unbalanced_haar(matrix::Matrix{Float64},jmax::Int;method::Symbol = :Totalvar, p::Float64 = 2.) Perform the quadtree partition of image matrix depending on total-variation or changes on the boundary. ### Input Arguments * `matrix`: The image matrix. * `jmax`: The maximum level of partition. * `method`: ':Totalvar' indicates using total variation, the other indicates using changes on the boundary. * `p`: The power used in the criterion to balance the sizes of the sub-regions. The larger `p`, the more weight on balancing the sub-regions. ### Output Arguments * `rse`: Region start and end. Each pair represents the start and end of a region in the matrix, corresponding to one node in the quadtree. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function PartitionTreeMatrix_unbalanced_haar(matrix::Matrix{Float64},jmax::Int;method::Symbol = :Totalvar, p::Float64 = 2.) rows,cols = size(matrix) N = rows*cols rse = Vector{Vector{Int}}(jmax) rse[1] = [1,N]; j = 1 while j<=jmax-1 rr = 1 rse[j+1] = zeros(4*length(rse[j])) for r = 1:2:(length(rse[j]) - 1) rs_rows,rs_cols = ind2sub((rows,cols),rse[j][r]) re_rows,re_cols = ind2sub((rows,cols),rse[j][r+1]) n_rows = re_rows-rs_rows+1 n_cols = re_cols-rs_cols+1 n1_rows,n1_cols = PartitionTreeMatrix_unbalanced_haar_subblock(matrix[rs_rows:re_rows,rs_cols:re_cols],method = method, p = p) if !(n1_rows==0 || n1_rows == n_rows) && !(n1_cols==0 ||n1_cols==n_cols) child_rows = [rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows, rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows]; child_cols = [rs_cols, rs_cols+n1_cols-1, rs_cols, rs_cols+n1_cols-1, rs_cols+n1_cols, re_cols, rs_cols+n1_cols, re_cols]; for k = 1:8 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 8 elseif (n1_rows == 0 || n1_rows == n_rows) && !(n1_cols == 0 || n1_cols == n_cols) child_rows = [rs_rows, re_rows, rs_rows, re_rows]; child_cols = [rs_cols, rs_cols+n1_cols-1, rs_cols+n1_cols, re_cols]; for k = 1:4 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 4 elseif (n1_cols == 0 || n1_cols == n_cols) && !(n1_rows == 0 || n1_rows == n_rows) child_rows = [rs_rows, rs_rows+n1_rows-1, rs_rows+n1_rows, re_rows]; child_cols = [rs_cols, re_cols, rs_cols, re_cols]; for k = 1:4 rse[j+1][rr+k-1] = sub2ind((rows,cols),child_rows[k],child_cols[k]) end rr = rr + 4 else rse[j+1][rr:rr+1] = rse[j][r:r+1] rr = rr + 2 end end j = j+1 rse[j] = rse[j][rse[j].!=0] end return rse end """ row_cut,col_cut = PartitionTreeMatrix_unbalanced_haar_subblock(matrix::Matrix{Float64};method::Symbol = :Totalvar, p::Float64 = 2.) Partition a matrix block into four sub-blocks. ### Input Arguments * `matrix`: The image matrix. * `method`: ':Totalvar' indicates using total variation, the other indicates using changes on the boundary. * `p`: The power used in the criterion to balance the sizes of the sub-regions. The larger `p`, the more weight on balancing the sub-regions. ### Output Arguments * `row_cut`: The cut index on the row direction. * `col_cut`: The cut index on the col direction. Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function PartitionTreeMatrix_unbalanced_haar_subblock(matrix::Matrix{Float64};method::Symbol = :Totalvar, p::Float64 = 2.) m,n = size(matrix) Entropy = Inf if m>1 && n>1 for i=1:m-1 for j=1:n-1 if method == :Totalvar Entropy_temp = total_var(matrix[1:i,1:j])/(i*j)^p + total_var(matrix[i+1:m,1:j])/((m-i)*j)^p + total_var(matrix[1:i,j+1:n])/(i*(n-j))^p + total_var(matrix[i+1:m,j+1:n])/((m-i)*(n-j))^p; else Entropy_temp = -( norm(matrix[i,:]-matrix[i+1,:],1) + norm(matrix[:,j] - matrix[:,j+1],1) )/((i*j)^(-p) + ((m-i)*j)^(-p) + (i*(n-j))^(-p) + ((m-i)*(n-j))^(-p)); end if Entropy_temp < Entropy Entropy = Entropy_temp row_cut = i col_cut = j end end end elseif m == 1 && n>1 row_cut = 0 for j = 1:n-1 if method == :Totalvar Entropy_temp = total_var(matrix[1,1:j])/j^p + total_var(matrix[1,j+1:n])/(n-j)^p; else Entropy_temp = -norm(matrix[:,j] - matrix[:,j+1],1)*(j^(-p) + (n-j)^(-p)); end if Entropy_temp < Entropy Entropy = Entropy_temp col_cut = j end end elseif n == 1 && m>1 col_cut = 0 for i = 1:m-1 if method == :Totalvar Entropy_temp = total_var(matrix[1:i,1])/i^p + total_var(matrix[i+1:m,1])/(m-i)^p; else Entropy_temp = -norm(matrix[i,:]-matrix[i+1,:],1)*(i^(-p) + (m-i)^(-p)); end if Entropy_temp < Entropy Entropy = Entropy_temp row_cut = i end end else row_cut = 0 col_cut = 0 end return row_cut,col_cut end """ v = total_var(matrix::Matrix{Float64}) Compute the total variation of matrix Copyright 2018 The Regents of the University of California Implemented by Yiqun Shao (Adviser: Dr. Naoki Saito) """ function total_var(matrix::Matrix{Float64}) m,n = size(matrix) row_val = abs.(matrix[1:m-1,:] - matrix[2:m,:]) col_val = abs.(matrix[:,1:n-1] - matrix[:,2:n]) v = norm(vcat(row_val[:],col_val[:]),1) return v end function PartitionTreeMatrix_unbalanced_haar_binarytree(matrix::Matrix{Float64}, jmax::Int64, p::Float64) N = size(matrix,2) rs = fill(0, N+1, jmax) rs[1,:] .= 1 rs[2,1] = N+1 for j = 1:jmax - 1 rr = 1 regioncount = sum(!iszero, rs[:,j]) - 1 for r = 1:regioncount rs1 = rs[r,j] rs2 = rs[r+1,j] n = rs2 - rs1 if n > 1 n1 = PartiitonTreeMatrix_unbalanced_haar_col_partition(matrix[:,rs1:rs2-1],p) rs[rr+1,j+1] = rs1+n1 rs[rr+2,j+1] = rs2 rr = rr+2 elseif n == 1 rs[rr+1,j+1] = rs2 rr = rr+1 end end end GP = GraphPart(Vector{Int}(1:N), rs) return GP end function PartiitonTreeMatrix_unbalanced_haar_col_partition(matrix::Matrix{Float64},p::Float64) n = size(matrix,2) entropy = Inf col_cut = 1 for j = 1:n-1 entropy_temp = total_var(matrix[:, 1:j])/(j^p) + total_var(matrix[:,j+1:n])/(n-j)^p if entropy_temp < entropy entropy = entropy_temp col_cut = j end end return col_cut end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
16768
using LinearAlgebra, AverageShiftedHistograms, Distances """ T = ind_class(N::Int) Given `N`, determine what class `ind` (and `rs`) should be ### Input Argument * `N::Int`: the length of the graph signal ### Output Argument * `T <: Unsigned`: the unsigned integer class that `ind` should be Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) | Translated and revised by Naoki Saito, Feb. 8, 2017 """ function ind_class(N::Int) if N < 2^8-2 T = UInt8 elseif N < 2^16-2 T = UInt16 elseif N < 2^32-2 T = UInt32 elseif N < 2^64-2 T = UInt64 else T = UInt128 # Hope this does not happen! end return T end """ T = tag_class(jmax::Int) Given `jmax`, determine what class `tag` should be. ### Input Argument * `jmax::Int`: the number of levels in the recursive partitioning (j = 1:jmax) ### Output Argument * `T <: Unsigned`: the unsigned integer class that `tag` should be Copyright 2015 The Regents of the University of California Implemented by Jeff Irion (Adviser: Dr. Naoki Saito) | Translated and revised by Naoki Saito, Feb. 8, 2017 """ function tag_class(jmax::Int) if jmax - 1 <= 8 T = UInt8 elseif jmax - 1 <= 16 T = UInt16 elseif jmax - 1 <= 32 T = UInt32 elseif jmax - 1 <= 64 T = UInt64 else T = UInt128 # Hope this does not happen! end return T end """ dmatrix_flatten(dmatrix::Array{Float64,3}, flatten::Any) Flatten dmatrix using the method specified by the string "flatten" ### Input Arguments * `dmatrix::Array{Float64,3}`: the matrix of expansion coefficients; after this function is called, it becomes the size of (~, ~, 1). * `flatten::Any`: the method for flattening dmatrix (see the code in details) """ function dmatrix_flatten(dmatrix::Array{Float64,3}, flatten::Any) # p-norms or p-quasinorms if isa(flatten, Number) if flatten == 1 dmatrix = sum(abs.(dmatrix), dims = 3) elseif flatten == 0 dmatrix = sum(dmatrix != 0, dims = 3) else dmatrix = (sum(abs.(dmatrix).^flatten, dims = 3)).^(1 / flatten) end # histogram # # # elseif strcmpi(flatten,'histogram') # not yet implemented # What I meant here was to implement ASH-like pdf estimation # followed by the entropy computation. # sum of absolute values = 1-norm elseif isa(flatten, Symbol) if flatten == :abs dmatrix = sum(abs.(dmatrix), dims = 3) # standard deviation elseif flatten == :std # MATLAB: dmatrix = std(dmatrix, 0, 3) dmatrix = std(dmatrix, dims = 3) # variance elseif flatten == :var dmatrix = var(dmatrix, dims = 3) # inverse variance elseif flatten == :invvar dmatrix = var(dmatrix, dims = 3) dmatrix[ abs.(dmatrix) < eps() ] = eps() dmatrix = dmatrix.^-1; # max coefficient - min coefficient elseif flatten == :minmax || flatten == :maxmin # MATLAB: dmatrix = max(dmatrix, [], 3) - min(dmatrix, [], 3) dmatrix = maximum(dmatrix, dims = 3) - minimum(dmatrix, dims = 3) # sum (no absolute value) elseif flatten == :sum dmatrix = sum(dmatrix, dims = 3) # the sum of the differences of consecutive coeffs elseif flatten == :sumdiff dmatrix = sum(dmatrix[:, :, 2:end] - dmatrix[:, :, 1:(end - 1)], dims = 3) # the sum of the absolute values of the differences of consecutive coeffs elseif flatten == :sumabsdiff dmatrix = sum(abs.(dmatrix[:, :, 2:end] - dmatrix[:, :, 1:(end - 1)]), dims = 3) # Shannon entropy elseif flatten === :entropy # MATLAB: p = abs(dmatrix)/norm(dmatrix[:], 'fro') # p = abs(dmatrix)/norm(dmatrix[:]) # dmatrix = sum(p. * log2(p), 3) # Normally, we flatten to get an energy matrix, and then take entropy dmatrix = sum(abs.(dmatrix).^2, dims = 3) # now, all the column vectors have the same norm, so normalize it. dmatrix /= sum(dmatrix[:, 1, 1]) # now, each column has a unit norm. dmatrix = sum(-dmatrix .* log2.(dmatrix), dims = 3) # threshold coefficients below 0.5*norm(dmatrix)/length(dmatrix) and sum elseif flatten == :sub # MATLAB: t = 0.5 * norm(dmatrix[:], 'fro') / numel(dmatrix) t = 0.5 * norm(dmatrix[:]) / length(dmatrix) dmatrix[abs.(dmatrix) .< t] = 0 dmatrix = sum(dmatrix, dims = 3) # ASH pdf estimation followed by the entropy computation. elseif flatten == :ash (N, jmax, fcols) = Base.size(dmatrix) for j = 1:jmax for i = 1:N # ASH pdf estimation h = ash(dmatrix[i, j, :]) # number of sampling points (default: 500) npts = length(h.density) # width of the sampling range (default: max - min + 1*std) width = h.rng[end] - h.rng[1] # normalize pdf pdf = h.density / norm(h.density, 1) # estimate of differential entropy by the limiting density # of discrete points (uniform sampling) dmatrix[i, j, 1] = entropy(pdf, 2.0) + log2(width / npts) end end # flatten dmatrix by slicing dmatrix = reshape(dmatrix[:, :, 1], N, jmax, 1) # default (1-norm) else @warn("the specified flatten symbol $(flatten) is not recognized; hence we assume it as 1-norm.") dmatrix = sum(abs.(dmatrix), dims = 3) end else @warn("the specified flatten argument $(flatten) is neither of number nor of symbol type; hence we assume it as 1-norm.") dmatrix = sum(abs.(dmatrix), dims = 3) end return dmatrix end # of function dmatrix_flatten! """ function ldb_discriminant_measure(p::Vector{Float64}, q::Vector{Float64}; dm::Symbol = :KLdivergence) Discriminat measure in LDB. ### Input Arguments * `p,q::Vector{Float64}`: probability mass functions. * `dm::Symbol`: discriminant measure. Options: `:KLdivergence`(default), `:Jdivergence`, `:l1`, `:l2`, and `:Hellinger`. """ function ldb_discriminant_measure(p::Vector{Float64}, q::Vector{Float64}; dm::Symbol = :KLdivergence) @assert all(p .>= 0) && all(q .>= 0) @assert length(p) == length(q) if dm == :KLdivergence ind = findall((p .> 0) .& (q .> 0)) return Distances.kl_divergence(p[ind], q[ind]) elseif dm == :Jdivergence ind = findall((p .> 0) .& (q .> 0)) return Distances.kl_divergence(p[ind], q[ind]) + Distances.kl_divergence(q[ind], p[ind]) elseif dm == :l1 return norm(p - q, 1) elseif dm == :l2 return norm(p - q, 2) elseif dm == :Hellinger return hellinger(p, q) else error("This discriminat measure $(dm) is not supported! ") end end """ function dmatrix_ldb_flatten(dmatrix::Array{Float64,3}...; dm::Symbol = :KLdivergence) Flatten dmatrices using the LDB method; after this function is called, it returns a matrix of size (~, ~, 1). ### Input Arguments * `dmatrix::Array{Float64,3}`: the matrix of LDB expansion coefficients in one class. * `dm::Symbol`: discriminant measure. Options: `:KLdivergence` (default), `:Jdivergence`, `:l1`, `:l2`, and `:Hellinger`. ### Example Usage: `dmatrix_ldb_flatten(dmatrix1, dmatrix2, dmatrix3)`, each argument is the expansion coefficient matrix of a class of signals. It uses the default discriminant measure KL divergence to flatten these matrices. In other words, it flattens these expansion coefficent matrices by computing and summing "statistical distances" among them. """ function dmatrix_ldb_flatten(dmatrix::Array{Float64,3}...; dm::Symbol = :KLdivergence) C = length(dmatrix) # number of signal classes if C < 2 error("Input should contain at least two classes of signals.") end N, jmax, _ = Base.size(dmatrix[1]) res = zeros(N, jmax) for u = 1:(C - 1), v = (u + 1):C for j = 1:jmax for i = 1:N h1 = ash(dmatrix[u][i, j, :]) p = h1.density / norm(h1.density, 1) h2 = ash(dmatrix[v][i, j, :]) q = h2.density / norm(h2.density, 1) res[i, j] += ldb_discriminant_measure(p, q; dm = dm) end end end res = reshape(res[:, :, 1], N, jmax, 1) return res end """ costfun = cost_functional(cfspec::Any) Determine the cost functional to be used by the best-basis algorithm. ### Input Argument * `cfspec::Any`: the specification for the cost functional ### Output Argument * `costfun::Function`: the cost functional (as a function_handle) """ function cost_functional(cfspec::Any) if isa(cfspec, Number) return function (x) return norm(x, cfspec) end elseif isa(cfspec, Function) return function (x) return cfspec(x) end else return function (x) return norm(x, 1) end # by default 1-norm # else return function (x) return norm(x, 0.1) end # by default 0.1-quasinorm end end # of function cost_functional # """ # (dvec, levlist) = bbchange(dvec::Vector{Float64}, j::Int) # # Change to the new best basis # # ### Input Arguments # * `dvec::Vector{Float64}`: an input coefficient matrix # * `j::Int`: a level index # # ### Output Arguments # * `dvec::Vector{Float64}`: an output coefficient matrix # * `levlist::Vector{Int}`: an output levlist # """ # function bbchange(dvec::Vector{Float64}, j::Int) # n = Base.size(dvec, 1) # assume each column corresponding to one signal # levlist = zeros(Int, n) # levlist[1] = j # return dvec, levlist # might need deepcopy here. # end """ function rs_to_region(rs::Matrix{Any}, tag::Matrix{Any}) From the imformation of rs, tag from GP, compute the tag_r matrix, which have the same size of dmatrix (expansion coefficient matrix). Each element indicates the place of the coefficient in the expansion tree. ### Input Arguments * `rs::Matrix{Any}`: rs from GP, showing information of the partition tree * `tag::Matrix{Any}`: tag from GP, indicating coefficients tag ### Output Arguments * `tag_r::Matrix{UInt64}`: showing information of the partition tree, same size as dmatrix """ function rs_to_region(rs::Matrix{Int}, tag::Matrix{Int}) (m,n) = size(tag) tag_r = zeros(m,n) for j = 1:(n-1) regioncount = count(!iszero, rs[:,j]) - 1 for r = 1:regioncount rs1 = rs[r,j] rs3 = rs[r+1,j] s = rs3-rs1 if s==1 #the region and subregion have only one element tag_r[rs1,j+1] = 2*tag_r[rs1,j] elseif s > 1 # rs2 marks the start of the second subregion rs2 = rs1 + 1 while rs2 < rs3 && tag[rs2, j+1]!=0 rs2 = rs2 + 1; end # the parent region is a copy of the subregion if rs2 == rs3 tag_r[rs1:rs3-1,j+1] = 2*tag_r[rs1:rs3-1,j] # the parent region has 2 child regions else tag_r[rs1:rs2-1,j+1] = 2*tag_r[rs1:rs2-1,j] tag_r[rs2:rs3-1,j+1] = 2*tag_r[rs2:rs3-1,j] .+ 1 end end end end return Matrix{Int}(tag_r) end """ function nonorth2relerror(nonorth::array{Float64,1},B::array{Float64,2}) Given a vector 'nonorth' of non-orthonormal expansion coefficients and the matrix 'B' such that B*nonorth is the original signal, return a vector of relative approximation errors when retaining the 1,2,...,N largest coefficients in magnitude. ### Input argument * `nonorth`: a vector of non-orthonormal expansion coefficients * `B`: the matrix whose such that B*nonorth is the original signal ### Output argument * `relerror`: a vector of relative approximation errors """ function nonorth2relerror(nonorth::Array{Float64,1},B::Array{Float64,2}) # sort the expansion coefficients IX = sortperm(nonorth, by = abs, rev = true) # generate a matrix where column j contains the j largest coefficients matrix0 = Matrix(UpperTriangular(repeat(nonorth[IX],1,length(IX)))) matrix = deepcopy(matrix0) matrix[IX,:] = matrix0 # the original signal and a matrix of reconstructions f = B*nonorth recons = B*matrix # the relative errors relerror = sum((repeat(f,1,length(IX)) - recons).^2, dims = 1)'.^(1/2)./norm(f,2) return relerror end """ function orth2relerror(orth) Given a vector 'orth' of orthonormal expansion coefficients, return a vector of relative approximation errors when retaining the 1,2,...,N largest coefficients in magnitude. ### Input argument * `orth`: a vector of orthonormal expansion coefficients ### Output argument * `relerror`: a vector of relative approximation errors """ function orth2relerror(orth::Array{Float64,1}) # sort the coefficients orth = sort(orth.^2, rev = true) #compute the relative errors relerror = ((abs.(sum(orth) .- cumsum(orth))).^(1/2))/sum(orth).^(1/2) return relerror end ## NGWP utils functions # project vector x onto matrix A's column space, given A is full column rank function Proj(x, A) y = try pinv(A' * A) * (A' * x) catch err if err != Nothing A' * x end end return A * y end function wavelet_perp_Matrix(w,A) N, k = size(A) B = zeros(N, k - 1) if k == 1 return end tmp = A'*w if tmp[1] > 1e-6 M = Matrix{Float64}(I, k-1, k-1) return A*vcat((-tmp[2:end] ./ tmp[1])', M) end if tmp[end] > 1e-6 M = Matrix{Float64}(I, k-1, k-1) return A*vcat(M,(-tmp[1:end-1] ./ tmp[end])') end ind = findall(tmp .== maximum(tmp))[1] rest_ind = setdiff([i for i in 1:k], ind) M = Matrix{Float64}(I, k-1, k-1) B = A * vcat(vcat(M[1:ind-1,:], (-tmp[rest_ind] ./ tmp[ind])'), M[ind:end, :]) return B end # Gram-Schmidt Process Orthogonalization function gram_schmidt(A; tol = 1e-12) # Input: matirx A # Output: orthogonalization matrix of A's column vectors # Convert the matrix to a list of column vectors a = [A[:,i] for i in 1:size(A,2)] # Start Gram-Schmidt process q = [] complement_dim = 0 for i = 1:length(a) qtilde = a[i] for j = 1:(i - 1) qtilde -= (q[j]' * a[i]) * q[j] end if norm(qtilde) < tol complement_dim = size(A,2) - i + 1 break end push!(q, qtilde / norm(qtilde)) end Q = zeros(size(A,1), length(q)) for i = 1:length(q) Q[:,i] .= q[i] end return Q, complement_dim end """ mgslp(A::Matrix{Float64}; tol::Float64 = 1e-12, p::Float64 = 1.0) Modified Gram-Schmidt Process Orthogonalization with ℓᵖ pivoting algorithm (MGSLp) # Input Arguments - `A::Matrix{Float64}`: whose column vectors are to be orthogonalized. # Output Argument - `A::Matrix{Float64}`: orthogonalization matrix of A's column vectors based on ℓᵖ pivoting. """ function mgslp(A::Matrix{Float64}; tol::Float64 = 1e-12, p::Float64 = 1.0) n = size(A, 2) # Convert the matrix to a list of column vectors a = [A[:, i] for i in 1:n] # Start modified Gram-Schmidt process q = [] v = copy(a) vec_lp_norm = [norm(v[i], p) for i in 1:n] complement_dim = 0 for i = 1:n # Pivoting based on minimum ℓᵖ-norm idx = findmin(vec_lp_norm)[2] v[i], v[idx + i - 1] = v[idx + i - 1], v[i] # Check the linear dependency if norm(v[i]) < tol complement_dim = n - i + 1 break end qtilde = v[i] / norm(v[i], 2) vec_lp_norm = [] for j = (i + 1):n v[j] .-= (qtilde' * v[j]) * qtilde push!(vec_lp_norm, norm(v[j], p)) end push!(q, qtilde) end Q = zeros(size(A,1), length(q)) for i = 1:length(q) Q[:,i] .= q[i] end return Q, complement_dim end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1907
""" varimax(A; gamma = 1.0, minit = 20, maxit = 1000, reltol = 1e-12) VARIMAX perform varimax (or quartimax, equamax, parsimax) rotation to the column vectors of the input matrix. # Input Arguments - `A::Matrix{Float64}`: input matrix, whose column vectors are to be rotated. d, m = size(A). - `gamma::Float64`: default is 1. gamma = 0, 1, m/2, and d(m - 1)/(d + m - 2), corresponding to quartimax, varimax, equamax, and parsimax. - `minit::Int`: default is 20. Minimum number of iterations, in case of the stopping criteria fails initially. - `maxit::Int`: default is 1000. Maximum number of iterations. - `reltol::Float64`: default is 1e-12. Relative tolerance for stopping criteria. # Output Argument - `B::Matrix{Float64}`: output matrix, whose columns are already been rotated. Implemented by Haotian Li, Aug. 20, 2019 """ function varimax(A; gamma = 1.0, minit = 20, maxit = 1000, reltol = 1e-12) # Get the sizes of input matrix d, m = size(A) # If there is only one vector, then do nothing. if m == 1 return A end if d == m && rank(A) == d return Matrix{Float64}(I, d, m) end # Warm up step: start with a good initial orthogonal matrix T by SVD and QR T = Matrix{Float64}(I, m, m) B = A * T L,_,M = svd(A' * (d*B.^3 - gamma*B * Diagonal(sum(B.^2, dims = 1)[:]))) T = L * M' if norm(T-Matrix{Float64}(I, m, m)) < reltol T = qr(randn(m,m)).Q B = A * T end # Iteration step: get better T to maximize the objective (as described in Factor Analysis book) D = 0 for k in 1:maxit Dold = D L,s,M = svd(A' * (d*B.^3 - gamma*B * Diagonal(sum(B.^2, dims = 1)[:]))) T = L * M' D = sum(s) B = A * T if (abs(D - Dold)/D < reltol) && k >= minit break end end # Adjust the sign of each rotated vector such that the maximum absolute value is positive. for i in 1:m if abs(maximum(B[:,i])) < abs(minimum(B[:,i])) B[:,i] .= - B[:,i] end end return B end
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
11635
# This is a very preliminary test function; # Just small scale examples, e.g., P6 with 10 random signals. More coming! using Test, MultiscaleGraphSignalTransforms, LinearAlgebra, SparseArrays, JLD2, Plots @testset "MultiscalGraphSignalTransforms.jl" begin ############################################################## # 1. Testing basic GHWT functions on 10 random signals on P6 # ############################################################## @testset "1. Testing basic GHWT functions" begin println("1. Testing basic GHWT functions") JLD2.@load "runtests_data/path6randn10.jld2" G G = gpath(6, G["tmp"]) GP = partition_tree_fiedler(G) dc2f = ghwt_analysis!(G, GP=GP) @testset "Check the Haar basis" begin BH=bs_haar(GP) dvec=dmatrix2dvec(dc2f, GP, BH) frecon=ghwt_synthesis(dvec,GP,BH) println("Relative L2 error of the Haar transform: ", norm(G.f-frecon)/norm(G.f)) @test norm(G.f-frecon)/norm(G.f) < 10 * eps() end @testset "Check the best basis and its expansion coefficients" begin bbc2f = ghwt_c2f_bestbasis(dc2f, GP) levlist = collect(enumerate([4; 4; 3; 3; 3; 3])) println("The true BB levlist: ", levlist) println("The comp BB levlist: ", bbc2f[2].levlist) println("They are equal: ", levlist == bbc2f[2].levlist) @test levlist == bbc2f[2].levlist JLD2.@load "runtests_data/bbcoef.jld2" tmp2 println("The relative L2 error of the BB coefs: ", norm(tmp2["bbcoef"]-bbc2f[1])/norm(tmp2["bbcoef"])) @test norm(tmp2["bbcoef"]-bbc2f[1])/norm(tmp2["bbcoef"]) < 10 * eps() end println("\n") end ################################################################ # 2. Testing GHWT/eGHWT functions on a simple synthetic signal on P6 # ################################################################ @testset "2. GHWT/eGHWT tests on P6" begin f = Array{Float64}([2. -2. 1. 3. -1. -2.]') G = gpath(6, f) GP = partition_tree_fiedler(G; method = :Lrw) dmatrix = ghwt_analysis!(G, GP=GP) println("2. Testing the GHWT functions on a path signal: ", f) println("The original signal has L1 norm: ", norm(f,1)) @testset "The full level GHWT best basis" begin dvec,BS = ghwt_bestbasis(dmatrix, GP, cfspec=1.) (f, GS) = ghwt_synthesis(dvec, GP, BS, G) println("The coefficient vectors of the GHWT best basis has L1 norm: ", norm(dvec,1)) println("Relative L2 error of the synthesized signal: ", norm(G.f-f)/norm(G.f)) @test norm(G.f-f)/norm(G.f) < 10 * eps() end @testset "The GHWT best basis restricted levels" begin j_start = 3 j_end = 4 dvec_restricted,BS_restricted = ghwt_bestbasis(dmatrix, GP, cfspec=1., j_start = j_start, j_end = j_end) (f_restricted, GS_restricted) = ghwt_synthesis(dvec_restricted, GP, BS_restricted, G) println("The coefficient vectors of the GHWT best basis restricted from level $(j_start) to level $(j_end) in c2f dictionary has L1 norm: ", norm(dvec_restricted,1)) println("Relative L2 error of the synthesized signal: ", norm(G.f-f_restricted)/norm(G.f)) @test norm(G.f-f_restricted)/norm(G.f) < 10 * eps() end @testset "The eGHWT best basis" begin dvec_tf, BS_tf = ghwt_tf_bestbasis(dmatrix, GP, cfspec=1.) (f_tf, GS_tf) = ghwt_synthesis(dvec_tf, GP, BS_tf, G) println("The coefficient vectors of the time-frequency adapted GHWT best basis has L1 norm: ", norm(dvec_tf,1)) println("Relative L2 error of the synthesized signal: ", norm(G.f-f_tf)/norm(G.f)) @test norm(G.f-f_tf)/norm(G.f) < 10 * eps() end println("\n") end ################################################################################# # 3. Testing time-frequency adapted 2D GHWT functions using a simple 3x3 matrix # ################################################################################# @testset "3. 2D GHWT/eGHWT on 3x3 matrix" begin println("3. Testing 2D GHWT/eGHWT functions") matrix = [ 1.0 2.0 3.0; 4.0 5.0 6.0] #matrix = matread("termdoc.mat")["matrix"] # expand matrix in 2 directions (rows and cols) GProws, GPcols = partition_tree_matrixDhillon(matrix) dmatrix = ghwt_analysis_2d(matrix, GProws, GPcols) # find the best basis using the time-frequency analysis # infovec indicate the location of each coefficient in dmatrix dvec_tf, infovec_tf = ghwt_tf_bestbasis_2d(matrix, GProws, GPcols) matrix_tf = ghwt_tf_synthesis_2d(dvec_tf, infovec_tf, GProws, GPcols) # find the best basis using the GHWT dvec_ghwt, BSrows, BScols = ghwt_bestbasis_2d(matrix, GProws, GPcols) matrix_ghwt = ghwt_synthesis_2d(dvec_ghwt, GProws, GPcols, BSrows, BScols) println("The toy matrix [1 2 3; 4 5 6] has 1-vecnorm as ", norm(matrix,1)) println("The eGHWT best basis of toy matrix [1 2 3; 4 5 6] has 1-vecnorm as ", norm(dvec_tf,1)) println("The GHWT best basis of toy matrix [1 2 3; 4 5 6] has 1-vecnorm as ", norm(dvec_ghwt,1)) println("Relative L2 error of the eGHWT synthesized matrix: ", norm(matrix - matrix_tf, 2)/norm(matrix,2)) @test norm(matrix - matrix_tf, 2)/norm(matrix,2) < 10 * eps() println("Relative L2 error of the GHWT synthesized matrix: ", norm(matrix - matrix_ghwt, 2)/norm(matrix,2)) @test norm(matrix - matrix_ghwt, 2)/norm(matrix,2) < 10 * eps() println("\n") end ################################################################### # 4. Testing HGLET functions and hybrid methods on a real dataset # ################################################################### @testset "4. HGLET on Toronto Street Network" begin println("4. HGLET on Toronto Street Network") #JLD2.@load "runtests_data/Dendrite.jld2" G #G = G["G"] # convert to SparseMatrixCSC{Float64,Int} where Int is machine dependent. #A = Array(G["W"]) #B = sparse(A) #G = GraphSig(B, xy = G["xy"], f = G["f"], name = G["name"]) JLD2.@load "runtests_data/Toronto_new.jld2" tmp1 = toronto["G"] G=GraphSig(tmp1["W"],xy=tmp1["xy"],f=tmp1["f"],name =tmp1["name"],plotspecs = tmp1["plotspecs"]) GP = partition_tree_fiedler(G) dmatrixH, dmatrixHrw, dmatrixHsym = HGLET_Analysis_All(G, GP) # expansion coefficients of 3-way HGLET bases dmatrixG = ghwt_analysis!(G,GP = GP) # expansion coefficients of GHWT dvec5,BS5,trans5,p5 = HGLET_GHWT_BestBasis_minrelerror(GP,G,dmatrixH = dmatrixH, dmatrixG = dmatrixG, dmatrixHrw = dmatrixHrw, dmatrixHsym = dmatrixHsym) # best-basis among all combinations of bases fS5, GS5 = HGLET_GHWT_Synthesis(reshape(dvec5,(size(dvec5)[1],1)),GP,BS5,trans5,G) println("The original signal has L1 norm: ", norm(G.f,1)) println("The coefficients of best-basis selected from hybrid method has L1 norm: ", norm(dvec5,1)) println("Relative L2 error of the synthesized signal: ", norm(G.f-fS5)/norm(G.f)) @test norm(G.f-fS5)/norm(G.f) < 10 * eps() println("\n") end ########################################################################### # 5. Testing GraphSig_Plot on mutilated Gaussian signal on the MN roadmap # ########################################################################### @testset "5. GraphSig_Plot on the MN roadmap" begin println("5. GraphSig_Plot on the MN roadmap") println("... this may not display the plot if you run it via the package test.") JLD2.@load "runtests_data/MN_MutGauss.jld2" G tmp1 = G["G"] G=GraphSig(tmp1["W"],xy=tmp1["xy"],f=tmp1["f"],name =tmp1["name"],plotspecs = tmp1["plotspecs"]) G = Adj2InvEuc(G) plt = GraphSig_Plot(G) display(plt) @test typeof(plt) == Plots.Plot{Plots.GRBackend} println("\n") end ################################################### # 6. Testing LP-HGLET functions on a real dataset # ################################################### @testset "6. LP-HGLET on RGC100" begin println("6. LP-HGLET on RGC100") JLD2.@load "runtests_data/Dendrite.jld2" G G = G["G_3D"] f = G["f"] G_Sig = GraphSig(1.0 * G["W"]; xy = G["xy"], f = f) G_Sig = Adj2InvEuc(G_Sig) GP = partition_tree_fiedler(G_Sig; swapRegion = false) dmatrixlH, _ = LPHGLET_Analysis_All(G_Sig, GP; ϵ = 0.3) dvec_lphglet, BS_lphglet, _ = HGLET_GHWT_BestBasis(GP, dmatrixH = dmatrixlH) fS, GS = LPHGLET_Synthesis(reshape(dvec_lphglet, (length(dvec_lphglet), 1)), GP, BS_lphglet, G_Sig; ϵ = 0.3) println("The original signal has L1 norm: ", norm(f, 1)) println("The coefficients of LP-HGLET best-basis has L1 norm: ", norm(dvec_lphglet, 1)) println("Relative L2 error of the synthesized signal: ", norm(f - fS) / norm(f)) @test norm(f - fS) / norm(f) < 20 * eps() println("\n") end ######################################################### # 7. Testing VM-NGWP, PC-NGWP, LP-NGWP functions on P64 # ######################################################### @testset "7. testing VM-NGWP/PC-NGWP/LP-NGWP on P64" begin println("7. testing VM-NGWP/PC-NGWP/LP-NGWP on P64") N = 64 G = gpath(N) # use Chebyshev polynomial T₅(x) (x ∈ [0, 1]) as the path signal G.f = reshape([16 * x^5 - 20 * x^3 + 5 * x for x in LinRange(0, 1, N)], (N, 1)) # compute graph Laplacian eigenvectors W = G.W L = diagm(sum(W; dims = 1)[:]) - W 𝛌, 𝚽 = eigen(L); 𝚽 = 𝚽 .* sign.(𝚽[1,:])' # build Gstar Gstar = GraphSig(W) GP = partition_tree_fiedler(G; swapRegion = false) GP_dual = partition_tree_fiedler(Gstar; swapRegion = false) GP_primal = pairclustering(𝚽, GP_dual) # for PC-NGWP # construct NGWP dictionaries VM_NGWP = vm_ngwp(𝚽, GP_dual) PC_NGWP = pc_ngwp(𝚽, GP_dual, GP_primal) LP_NGWP = lp_ngwp(𝚽, W, GP_dual; ϵ = 0.3) # NGWP analysis dmatrix_VM = ngwp_analysis(G, VM_NGWP) dvec_vm_ngwp, BS_vm_ngwp = ngwp_bestbasis(dmatrix_VM, GP_dual) dmatrix_PC = ngwp_analysis(G, PC_NGWP) dvec_pc_ngwp, BS_pc_ngwp = ngwp_bestbasis(dmatrix_PC, GP_dual) dmatrix_LP = ngwp_analysis(G, LP_NGWP) dvec_lp_ngwp, BS_lp_ngwp = ngwp_bestbasis(dmatrix_LP, GP_dual) println("The original signal has L2 norm: ", norm(G.f)) println("The coefficients of VM-NGWP best-basis has L2 norm: ", norm(dvec_vm_ngwp)) @test abs(norm(G.f) - norm(dvec_vm_ngwp)) / norm(G.f) < 10 * eps() println("The coefficients of PC-NGWP best-basis has L2 norm: ", norm(dvec_pc_ngwp)) @test abs(norm(G.f) - norm(dvec_pc_ngwp)) / norm(G.f) < 10 * eps() println("The coefficients of LP-NGWP best-basis has L2 norm: ", norm(dvec_lp_ngwp)) @test abs(norm(G.f) - norm(dvec_lp_ngwp)) / norm(G.f) < 10 * eps() println("\n") end end # End of runtests.jl
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1082
cd(@__DIR__); include("setups/path128.jl") gr(dpi = 200) l = 64 𝛍 = nat_spec_filter(l, distDCT; σ = 0.05 * maximum(distDCT)) plot(0:N-1, 𝛍, legend = true, c = :blue, grid = false, frame = :box, marker = :circle, ms = 3, lw = 1, mswidth = 0, lab = latexstring("\\sigma=0.05 \\cdot d_{\\max}")) 𝛍 = nat_spec_filter(l, distDCT; σ = 0.1 * maximum(distDCT)) plot!(0:N-1, 𝛍, legend = true, c = :red, grid = false, frame = :box, marker = :circle, ms = 3, lw = 1, mswidth = 0, lab = latexstring("\\sigma=0.1 \\cdot d_{\\max}")) 𝛍 = nat_spec_filter(l, distDCT; σ = 0.2 * maximum(distDCT)) plot!(0:N-1, 𝛍, ylim = [0, 0.1], legend = true, c = :green, grid = false, frame = :box, marker = :circle, ms = 3, lw = 1, mswidth = 0, lab = latexstring("\\sigma=0.2 \\cdot d_{\\max}"), tickfontsize=10, legendfontsize = 12) xticks!([0; 15:16:127], vcat(string("DC"), [string(k) for k in 15:16:127])) plot!(xlab = latexstring("i"), ylab = latexstring("\\mu_{63}"), guidefontsize = 16) plt = current() savefig(plt, "../figs/Path128_NSGfilters_mu$(l-1).png") display(plt)
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1189
cd(@__DIR__); include("setups/simpletree.jl") gr(dpi = 200) ## build frames SGWT = sgwt_frame(Matrix(W); nf = 6) SGWT = reshape(SGWT, (N, :)) SGWT_dual = (SGWT * SGWT') \ SGWT distROT = natural_eigdist(𝚽, 𝛌, Q; α = 1.0, input_format = :pmf1, distance = :ROT) rNGWF, dic_l2x = rngwf_all_vectors(distROT, 𝚽; σ = 0.1 * maximum(distROT), thres = 0.15) rNGWF_dual = (rNGWF * rNGWF') \ rNGWF Γ = rngwf_lx(dic_l2x) ## (a) plt = plot(size = (600, 500)) gplot!(W, X, width = 1) scatter_gplot!(X; marker = f, ms = 4) plot!(frame = :none, cbar = true, xlim = [-10, 14]) savefig(plt, "../figs/simpletree_f.png") ## (b) rel_approx_sgwt, f_approx_sgwt = frame_approx(f, SGWT, SGWT_dual; num_kept = 3 * N) rel_approx_rngwf, f_approx_rngwf = frame_approx(f, rNGWF, rNGWF_dual; num_kept = 3 * N) plt = plot(0:length(rel_approx_rngwf)-1, [rel_approx_sgwt rel_approx_rngwf], grid = false, lw = 2, c = [:blue :green], xlab = "Number of Coefficients Retained", ylab = "Relative Approximation Error", yaxis = :log, lab = ["SGWT" "rNGWF"]) plot!(xguidefontsize = 14, yguidefontsize = 14, legendfontsize = 11, size = (600, 500)) savefig(plt, "../figs/simpletree_approx_f.png")
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
735
cd(@__DIR__); include("setups/simpletree.jl") gr(dpi = 200) ## build SGWT frame SGWT = sgwt_frame(Matrix(W); nf = 6) SGWT = reshape(SGWT, (N, :)) important_idx = sortperm((SGWT' * f).^2; rev = true) plot(layout = Plots.grid(3, 7), size = (1400, 1500)) for i = 1:21 ind = important_idx[i] j = Int(floor(ind / N)) x = ind - j * N w = SGWT[:, ind] w ./= norm(w, 2) scatter!(X[:, 1], X[:, 2], marker_z = w, ms = 5, c = :viridis, subplot = i, mswidth = 0) plot!(frame = :none, cbar = false, grid = false, legend = false, subplot = i) plot!(title = latexstring("\\psi^{\\mathrm{SGWT}}_{", j, ",", x, "}"), titlefont = 18, subplot = i) end plt = current() savefig(plt, "../figs/simpletree_f_sgwt_top21.png")
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
1020
cd(@__DIR__); include("setups/simpletree.jl") gr(dpi = 200) ## build rNGWF distROT = natural_eigdist(𝚽, 𝛌, Q; α = 1.0, input_format = :pmf1, distance = :ROT) rNGWF, dic_l2x = rngwf_all_vectors(distROT, 𝚽; σ = 0.1 * maximum(distROT), thres = 0.15) Γ = rngwf_lx(dic_l2x) just_eigenvec = [2, 16] important_idx = sortperm((rNGWF' * f).^2; rev = true) plot(layout = Plots.grid(3, 7), size = (1400, 1500)) for i = 1:21 l, x = Γ[important_idx[i]] w = rNGWF[:, important_idx[i]] w ./= norm(w, 2) scatter!(X[:, 1], X[:, 2], marker_z = w, ms = 5, c = :viridis, subplot = i, mswidth = 0) plot!(frame = :none, cbar = false, grid = false, legend = false, subplot = i) if l in just_eigenvec plot!(title = latexstring("\\bar{\\psi}_{", l, ",", x, "} \\equiv \\mathbf{\\phi}_{$(l)}"), titlefont = 18, subplot = i) else plot!(title = latexstring("\\bar{\\psi}_{", l, ",", x, "}"), titlefont = 18, subplot = i) end end plt = current() savefig(plt, "../figs/simpletree_f_rngwf_top21.png")
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git
[ "BSD-3-Clause" ]
1.7.3
b7903b11d1aa4a96fc63d04de036236099cf8608
code
621
cd(@__DIR__); include("setups/simpletree.jl") gr(dpi = 200) ## ind_eig = [5, 6, 11, 18, 21, 25, 38] plot(layout = Plots.grid(1, 7), size = (1400, 500)) for i = 1:length(ind_eig) l = ind_eig[i] w = 𝚽[:, l] scatter!(X[:, 1], X[:, 2], marker_z = w, ms = 5, c = :viridis, subplot = i, mswidth = 0) plot!(frame = :none, cbar = false, grid = false, legend = false, subplot = i) plot!(title = latexstring("\\mathbf{\\phi}_{", l - 1, "}"), titlefont = 18, subplot = i) end plot!(subplot = 10, grid = false, frame = :none) plt = current() savefig(plt, "../figs/simpletree_f_rngwf_top21_ref_eigenvectors.png")
MultiscaleGraphSignalTransforms
https://github.com/UCD4IDS/MultiscaleGraphSignalTransforms.jl.git