licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 9469 | #-------------------------------------------------------------------------------------------------------------------------
"""
SchmidtMatrix{Tm, Ta<:SubArray, Tb<:SubArray, Ti<:Integer}
Struct that is used to construct the Schmidt matrix:
`|Ψ⟩ = ∑ᵢⱼ Mᵢᵢ|ψᵢ⟩ ⊗ |ψⱼ⟩`
Properties:
-----------
- `M` : Schidt matrix.
- `A` : View of region A.
- `B` : View of region B.
- `base`: Base.
"""
struct SchmidtMatrix{Tm <: Number, Ta <: SubArray, Tb <: SubArray, Ti <: Integer}
M::Matrix{Tm}
A::Ta
B::Tb
base::Ti
end
#-------------------------------------------------------------------------------------------------------------------------
"""
SchmidtMatrix(T, b::AbstractBasis, Ainds::AbstractVector)
Construction of `SchmidtMatrix`.
"""
function SchmidtMatrix(T::DataType, b::AbstractBasis, Ainds::AbstractVector{Ta}) where Ta <: Integer
L = length(b)
B = b.B
Binds = Vector{Ta}(undef, L-length(Ainds))
P = 1
for i in range(one(Ta), stop=convert(Ta, L))
if !in(i, Ainds)
Binds[P] = i
P += 1
end
end
M = zeros(T, B^length(Ainds), B^length(Binds))
SchmidtMatrix(M, view(b.dgt, Ainds), view(b.dgt, Binds), B)
end
#-------------------------------------------------------------------------------------------------------------------------
function addto!(S::SchmidtMatrix, val::Number)
ia = index(S.A, base=S.base)
ib = index(S.B, base=S.base)
S.M[ia, ib] += val
end
#-------------------------------------------------------------------------------------------------------------------------
# Entanglement Entropy
#-------------------------------------------------------------------------------------------------------------------------
"""
ent_spec(v::AbstractVector, Aind::AbstractVector{<:Integer}, b::AbstractBasis)
Conpute the entanglement spectrum.
"""
ent_spec(v::AbstractVector, Aind::AbstractVector{<:Integer}, b::AbstractBasis) = svdvals(schmidt(v, Aind, b))
#-------------------------------------------------------------------------------------------------------------------------
"""
entropy(s::AbstractVector{<:Real}; α::Real=1, cutoff::Real=1e-20)
Compute the entropy of Schmidt values.
Inputs:
-------
- `s` : Schmidt values.
- `α` : Renyi index.
- `cutoff`: Cutoff of the Schmidt values.
Outputs:
--------
- `S`: Entanglement entropy.
"""
function entropy(s::AbstractVector{<:Real}; α::Real=1, cutoff::Real=1e-20)
if isone(α)
shannon_entropy(s, cutoff=cutoff)
elseif iszero(α)
renyi_zero_entropy(s, cutoff=cutoff)
else
renyi_entropy(s, α)
end
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Compute Shannon entropy
"""
function shannon_entropy(s::AbstractVector{<:Real}; cutoff::Real=1e-20)
ent = 0.0
for si in s
si > cutoff || break
ent -= si * log(si)
end
ent
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Compute Renyi-0 entropy, which is thenumber of non-zero Schmidt values.
"""
function renyi_zero_entropy(s::AbstractVector{<:Real}; cutoff::Real=1e-20)
N = 0
for si in s
si > cutoff || break
N += 1
end
N
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Compute general Renyi entropy
"""
renyi_entropy(s::AbstractVector{<:Real}, α::Real) = log(sum(s.^α)) / (1-α)
#-------------------------------------------------------------------------------------------------------------------------
export ent_S
"""
ent_S(v::AbstractVector, Aind::AbstractVector{<:Integer}, b::AbstractBasis; α::Real=1, cutoff::Real=1e-20)
Conpute the entanglement entropy of a state.
"""
function ent_S(v::AbstractVector, Aind::AbstractVector{<:Integer}, b::AbstractBasis; α::Real=1, cutoff::Real=1e-20)
s = ent_spec(v, Aind, b) .^ 2
entropy(s, α=α, cutoff=cutoff)
end
#-------------------------------------------------------------------------------------------------------------------------
function ent_S(v::AbstractVector, Aind::AbstractVector{<:Integer}, L::Integer; α::Real=1, cutoff::Real=1e-20)
b = TensorBasis(L, base=round(Int, length(v)^(1/L) ) )
s = ent_spec(v, Aind, b) .^ 2
entropy(s, α=α, cutoff=cutoff)
end
#-------------------------------------------------------------------------------------------------------------------------
# Specific Bases
#-------------------------------------------------------------------------------------------------------------------------
"""
schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::AbstractOnsiteBasis)
Schmidt decomposition of state `v`, with respect to given lattice bipartition.
Inputs:
-------
- `v` : State represented by a (abstract) vector.
- `Ainds`: List of indices in subsystem `A`, the remaining indices are regarded as subsystem `B`.
- `b` : Basis.
Outputs:
--------
- `S`: Matrix S in the decomposition: |v⟩ = Sᵢⱼ |Aᵢ⟩|Bⱼ⟩.
"""
function schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::AbstractOnsiteBasis)
S = SchmidtMatrix(eltype(v), b, Ainds)
for i = 1:length(v)
change!(b, i)
addto!(S, v[i])
end
S.M
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Schmidt decomposition for `TranslationalBasis`.
"""
function schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::TranslationalBasis)
dgt, R, phase = b.dgt, b.R, b.C[2]
S = SchmidtMatrix(promote_type(eltype(v), eltype(b)), b, Ainds)
for i = 1:length(v)
change!(b, i)
val = v[i] / R[i]
for j in 1:length(dgt)÷b.A
addto!(S, val)
circshift!(dgt, b.A)
val *= phase
end
end
S.M
end
#-------------------------------------------------------------------------------------------------------------------------
"""
spinflip(v::AbstractVector{<:Integer}, base::Integer)
Flip spins Sz on each site.
"""
function spinflip(v::AbstractVector{<:Integer}, base::Integer)
vf = Vector{eltype(v)}(undef, length(v))
base -= 1
for i = 1:length(vf)
vf[i] = base - v[i]
end
vf
end
function spinflip!(v::AbstractVector{<:Integer}, base::Integer)
base -= 1
for i in eachindex(v)
v[i] = base - v[i]
end
v
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Helper function for `schmidt` on parity basis.
"""
function parity_schmidt(parity, v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::AbstractTranslationalParityBasis)
dgt, R, phase = b.dgt, b.R, b.C[2]
S = SchmidtMatrix(promote_type(eltype(v), eltype(b)), b, Ainds)
for i = 1:length(v)
change!(b, i)
val = v[i] / R[i]
for j in 1:length(dgt)÷b.A
addto!(S, val)
circshift!(dgt, b.A)
val *= phase
end
dgt .= parity(dgt)
val *= b.P
for j in 1:length(dgt)÷b.A
addto!(S, val)
circshift!(dgt, b.A)
val *= phase
end
end
S.M
end
#-------------------------------------------------------------------------------------------------------------------------
schmidt(v, Ainds, b::TranslationParityBasis) = parity_schmidt(reverse, v, Ainds, b)
schmidt(v, Ainds, b::TranslationFlipBasis) = parity_schmidt(x -> spinflip(x, b.B), v, Ainds, b)
#-------------------------------------------------------------------------------------------------------------------------
"""
Schmidt decomposition for `FlipBasis`.
"""
function schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::FlipBasis)
dgt, R, phase = b.dgt, b.R, b.P
S = SchmidtMatrix(promote_type(eltype(v), eltype(b)), b, Ainds)
for i = 1:length(v)
change!(b, i)
val = v[i] / R[i]
addto!(S, val)
dgt .= spinflip(dgt, b.B)
addto!(S, phase * val)
end
S.M
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Schmidt decomposition for `ParityBasis`.
"""
function schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::ParityBasis)
dgt, R, phase = b.dgt, b.R, b.P
S = SchmidtMatrix(promote_type(eltype(v), eltype(b)), b, Ainds)
for i = 1:length(v)
change!(b, i)
val = v[i] / R[i]
addto!(S, val)
reverse!(dgt)
addto!(S, phase * val)
end
S.M
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Schmidt decomposition for `ParityBasis`.
"""
function schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::ParityFlipBasis)
dgt, R, p1, p2 = b.dgt, b.R, b.P, b.Z
S = SchmidtMatrix(promote_type(eltype(v), eltype(b)), b, Ainds)
for i = 1:length(v)
# (P,Z) = (0,0)
change!(b, i)
val = v[i] / R[i]
addto!(S, val)
# (P,Z) = (1,0)
reverse!(dgt)
val *= p1
addto!(S, val)
# (P,Z) = (1,1)
dgt .= spinflip(dgt, b.B)
val *= p2
addto!(S, val)
# (P,Z) = (0,1)
reverse!(dgt)
val *= p1
addto!(S, val)
end
S.M
end | EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 2311 | #-------------------------------------------------------------------------------------------------------------------------
# Level statistics
#-------------------------------------------------------------------------------------------------------------------------
export gapratio, meangapratio
function gapratio(E::AbstractVector{<:Real})
dE = diff(E)
r = zeros(length(dE)-1)
for i = 1:length(r)
if dE[i] < dE[i+1]
r[i] = dE[i]/dE[i+1]
elseif dE[i] > dE[i+1]
r[i] = dE[i+1]/dE[i]
else
r[i] = 1.0
end
end
r
end
meangapratio(E::AbstractVector{<:Real}) = sum(gapratio(E)) / (length(E) - 2)
#-------------------------------------------------------------------------------------------------------------------------
# LinearAlgebra
#-------------------------------------------------------------------------------------------------------------------------
"""
expm(A, order::Integer=10)
Matrix exponential using Taylor expansion.
"""
function expm(A; order::Integer=10)
mat = I + A / order
order -= 1
while order > 0
mat = A * mat
mat ./= order
mat += I
order -= 1
end
mat
end
#-------------------------------------------------------------------------------------------------------------------------
"""
expv(A, v::AbstractVecOrMat; order=10, λ=1)
Compute exp(λA)*v using Taylor expansion
"""
function expv(A, v::AbstractVecOrMat; order::Integer=10, λ::Number=1)
vec = v + λ * A * v / order
order -= 1
while order > 0
vec = λ * A * vec
vec ./= order
vec += v
order -= 1
end
vec
end
#-----------------------------------------------------------------------------------------------------
# State
#-----------------------------------------------------------------------------------------------------
export productstate
"""
productstate(v::AbstractVector{<:Integer}, B::AbstractBasis)
Construction for product state.
Inputs:
-------
- `v`: Vector representing the product state.
- `B`: Basis.
Outputs:
- `s`: Vector representing the many-body state.
"""
function productstate(v::AbstractVector{<:Integer}, B::AbstractBasis)
s = zeros(size(B, 1))
B.dgt .= v
I = index(B)[2]
s[I] = 1
s
end | EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6844 | #-------------------------------------------------------------------------------------------------------------------------
# Abelian Operator
#-------------------------------------------------------------------------------------------------------------------------
struct AbelianOperator{Tp <: Number}
s::Vector{Int}
g::Vector{Int}
c::Vector{Vector{Tp}}
f::Vector
end
#-------------------------------------------------------------------------------------------------------------------------
function AbelianOperator(g::Int, k::Integer, f)
c = if iszero(k)
ones(g)
elseif 2k == g
[iseven(j) ? 1 : -1 for j in 0:g-1]
else
phase = 1im * 2π * k / g
[exp(phase * j) for j in 0:g-1]
end
AbelianOperator([1], [g], [c], [f])
end
#-------------------------------------------------------------------------------------------------------------------------
function +(g1::AbelianOperator, g2::AbelianOperator)
AbelianOperator([g1.s; g2.s], [g1.g; g2.g], [g1.c; g2.c], [g1.f; g2.f])
end
#-------------------------------------------------------------------------------------------------------------------------
function order(g::AbelianOperator)
prod(g.g)
end
#-------------------------------------------------------------------------------------------------------------------------
function phase(g::AbelianOperator)
prod(g.c[i][g.s[i]] for i in eachindex(g.c))
end
#-------------------------------------------------------------------------------------------------------------------------
function init!(g::AbelianOperator)
for i in eachindex(g.s)
g.s[i] = 1
end
g
end
#-------------------------------------------------------------------------------------------------------------------------
function (ag::AbelianOperator)(dgt::Vector)
for i in eachindex(ag.s)
ag.f[i](dgt)
(ag.s[i] = ag.s[i] + 1) > ag.g[i] ? (ag.s[i] = 1) : break
end
dgt
end
#-------------------------------------------------------------------------------------------------------------------------
function check_min(dgt, g::AbelianOperator; base=2)
init!(g)
I0 = index(dgt; base)
N = 1
for _ in 2:order(g)
g(dgt)
In = index(dgt; base)
if In < I0
return false, 0
elseif In == I0
abs(phase(g)-1) < 1e-14 || return false, 0
N += 1
end
end
true, N
end
#-------------------------------------------------------------------------------------------------------------------------
function shift_canonical!(dgt, g::AbelianOperator; base=2)
init!(g)
Im = index(dgt; base)
ms = g.s[:]
for _ in 1:order(g)
g(dgt)
In = index(dgt; base)
if In < Im
Im = In
ms .= g.s
end
end
g.s .= ms
Im, g
end
#-------------------------------------------------------------------------------------------------------------------------
# Abelian Basis
#-------------------------------------------------------------------------------------------------------------------------
struct AbelianBasis{Ti <: Integer, Tg <: Number} <: AbstractPermuteBasis
dgt::Vector{Ti} # Digits
I::Vector{Ti} # Representing states
R::Vector{Float64} # Normalization
G::AbelianOperator{Tg} # Generator
B::Ti # Base
end
#-------------------------------------------------------------------------------------------------------------------------
function AbelianBasis(
dtype::DataType=Int64;
L::Integer, G::AbelianOperator, base::Integer=2, f=x->true,
alloc=1000, threaded::Bool=true
)
Ng = order(G)
C = zeros(Ng)
for i in eachindex(C)
iszero(mod(Ng, i)) && (C[i] = sqrt(Ng * i))
end
I, R = if threaded
nt = Threads.nthreads()
ni = dividerange(base^L, nt)
nI = Vector{Vector{dtype}}(undef, nt)
nR = Vector{Vector{Float64}}(undef, nt)
Threads.@threads for ti in 1:nt
nI[ti], nR[ti] = _abelian_select(f, deepcopy(G), L, ni[ti], C; base, alloc)
end
vcat(nI...), vcat(nR...)
else
_abelian_select(f, G, L, 1:base^L, C; base, alloc)
end
AbelianBasis(zeros(dtype, L), I, R, G, base)
end
function _abelian_select(
f,
G,
L::Integer,
rg::UnitRange{T},
C;
base::Integer=2,
alloc::Integer=1000
) where T <: Integer
dgt = zeros(T, L)
Is = T[]
Rs = Float64[]
sizehint!(Is, alloc)
sizehint!(Rs, alloc)
for i in rg
change!(dgt, i; base)
f(dgt) || continue
Q, n = check_min(dgt, G; base)
Q || continue
push!(Is, i)
push!(Rs, C[n])
end
Is, Rs
end
#-------------------------------------------------------------------------------------------------------------------------
function index(B::AbelianBasis)
Im, g = shift_canonical!(B.dgt, B.G; base=B.B)
ind = binary_search(B.I, Im)
if iszero(ind)
return zero(eltype(B)), one(eltype(B.I))
else
return phase(g) * B.R[ind], ind
end
end
#-------------------------------------------------------------------------------------------------------------------------
function schmidt(v::AbstractVector, Ainds::AbstractVector{<:Integer}, b::AbelianBasis)
dgt, R, g = b.dgt, b.R, b.G
S = SchmidtMatrix(promote_type(eltype(v), eltype(b)), b, Ainds)
for i in eachindex(v)
init!(g)
change!(b, i)
val = v[i] / R[i]
addto!(S, val)
for _ in 2:order(g)
g(dgt)
addto!(S, phase(g) * val)
end
end
S.M
end
#-------------------------------------------------------------------------------------------------------------------------
export basis
function basis(
dtype::DataType=Int64;
L::Integer,
f=nothing,
base::Integer=2,
N::Union{Nothing, Integer}=nothing,
k::Union{Nothing, Integer}=nothing, a::Integer=1,
p::Union{Nothing, Integer}=nothing,
z::Union{Nothing, Integer}=nothing,
threaded::Bool=base^L>3000
)
gs = AbelianOperator[]
isnothing(k) || push!(gs, AbelianOperator(L, k, x -> circshift!(x, a)))
isnothing(p) || push!(gs, AbelianOperator(2, isone(-p) ? 1 : 0, reverse!))
isnothing(z) || push!(gs, AbelianOperator(2, isone(-z) ? 1 : 0, x -> spinflip!(x, base)))
if isempty(gs)
isnothing(f) && isnothing(N) && return TensorBasis(;L, base)
return ProjectedBasis(dtype; L, f, N, base, threaded)
else
g = if isnothing(N)
isnothing(f) ? x -> true : f
else
num = L*(base-1)-N
isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
end
return AbelianBasis(dtype; L, G=sum(gs), base, f=g, threaded)
end
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6834 | export AbstractBasis, content, base, index, change!
"""
AbstractBasis
Abstract type for all concrete `Basis` types.
The most important function for a `Basis` type is the index of a given digits and the digits representation of its ith content:
- `index` : Return the norm and the index of the digits of the given basis.
- `change!`: Change the digits to the target index, and return the new normalization.
If we want to calculate the schmidt decomposition (in real space), we can use the `schmidt` function.
"""
abstract type AbstractBasis end
abstract type AbstractOnsiteBasis <: AbstractBasis end
abstract type AbstractPermuteBasis <: AbstractBasis end
abstract type AbstractTranslationalParityBasis <: AbstractPermuteBasis end
#-------------------------------------------------------------------------------------------------------------------------
# Default function definitions
#-------------------------------------------------------------------------------------------------------------------------
"""
content(b::AbstractBasis, i::Integer)
Return index of ith vector in this basis.
"""
content(b::AbstractBasis, i::Integer) = b.I[i]
#-------------------------------------------------------------------------------------------------------------------------
"""
norm(b::AbstractBasis, i::Integer)
Return norm of ith vector in this basis.
"""
norm(b::AbstractBasis, i::Integer) = b.R[i]
norm(::AbstractOnsiteBasis, ::Integer) = 1
#-------------------------------------------------------------------------------------------------------------------------
"""
eltype(b::AbstractBasis)
Element data type of the basis.
- Return `Int64` for onsite basis.
- Return `ComplexF64` by default otherwise.
Used for type promotion when constructing matrix representation of an `Operator`.
"""
eltype(::AbstractBasis) = ComplexF64
eltype(::AbstractOnsiteBasis) = Int64
#-------------------------------------------------------------------------------------------------------------------------
"""
length(b::AbstractBasis)
Length of the digits.
"""
length(b::AbstractBasis) = length(b.dgt)
#-------------------------------------------------------------------------------------------------------------------------
"""
size(b::AbstractBasis, [dim])
Dimension of the `Operator` object construct by the basis.
"""
function size(b::AbstractBasis, dim::Integer)
isone(dim) && return length(b.I)
isequal(dim, 2) ? length(b.I) : 1
end
size(b::AbstractBasis) = (size(b, 1), size(b, 2))
#-------------------------------------------------------------------------------------------------------------------------
"""
change!(b::AbstractBasis, i::Integer)
Change the digits to the target index, and return the new normalization.
"""
function change!(b::AbstractBasis, i::Integer)
change!(b.dgt, content(b, i), base=b.B)
norm(b, i)
end
#-------------------------------------------------------------------------------------------------------------------------
"""
int_type(b::AbstractBasis)
Return index data type.
This is for basis with large indices exceeding the upper bound of `Int64`.
"""
int_type(b::AbstractBasis) = eltype(b.I)
#-----------------------------------------------------------------------------------------------------
# TensorBasis
#-----------------------------------------------------------------------------------------------------
export TensorBasis
"""
TensorBasis
Basis without any symmetries. The index is computed by:
I(i₁, i₂, ⋯, iₙ) = i₁ B^(n-1) + i₂ B^(n-2) + ⋯ + iₙ
In many bases this basis need not be constructed explicitly.
"""
struct TensorBasis <: AbstractOnsiteBasis
dgt::Vector{Int64}
B::Int64
end
function TensorBasis(;L::Integer, base::Integer=2)
dgt = zeros(Int64, L)
B = Int64(base)
TensorBasis(dgt, B)
end
#-------------------------------------------------------------------------------------------------------------------------
content(::TensorBasis, i::Integer) = i
norm(b::TensorBasis, ::Integer) = 1
eltype(::TensorBasis) = Int64
size(b::TensorBasis, i::Integer) = isone(i) || isequal(i, 2) ? b.B^length(b.dgt) : 1
size(b::TensorBasis) = (l=b.B^length(b.dgt); (l, l))
index(b::TensorBasis) = 1, index(b.dgt, base=b.B)
int_type(::TensorBasis) = Int64
#-------------------------------------------------------------------------------------------------------------------------
"""
copy(b::TensorBasis)
Copy basis with a deep copied `dgt`.
"""
function copy(b::TensorBasis)
TensorBasis(deepcopy(b.dgt), b.B)
end
#-------------------------------------------------------------------------------------------------------------------------
# Index functions
#-------------------------------------------------------------------------------------------------------------------------
"""
index(dgt::AbstractVector{T}; base::Integer=2, dtype::DataType=T) where T <: Integer
Convert a digits to the integer index using the relation:
number = ∑ᵢ bits[i] * base^(L-i) + 1
The summaton is evaluate using the efficieint polynomial evaluation method.
Inputs:
-------
- `dgt` : Digits.
- `base` : Base.
"""
@inline function index(dgt::AbstractVector{<:Integer}; base::T=2) where T <: Integer
N = zero(T)
for i = 1:length(dgt)
N *= base
N += dgt[i]
end
N + one(T)
end
#-------------------------------------------------------------------------------------------------------------------------
"""
index(dgt::AbstractVector{T}, sites::AbstractVector{<:Integer}; base::Integer=2) where T <: Integer
Convert a sub-digits (subarray of `dgt`) to the integer index.
"""
@inline function index(dgt::AbstractVector{T}, sites::AbstractVector{<:Integer}; base::T=2) where T <: Integer
N = zero(T)
for i in sites
N *= base
N += dgt[i]
end
N + one(T)
end
#-------------------------------------------------------------------------------------------------------------------------
"""
change!(dgt::AbstractVector{<:Integer}, ind::Integer; base::Integer=2)
Change the digits to that with the target index.
This method is the inverse of `index`.
"""
@inline function change!(dgt::AbstractVector{T}, ind::T; base::T=2) where T
N = ind - one(T)
for i = length(dgt):-1:1
N, dgt[i] = divrem(N, base)
end
end
#-------------------------------------------------------------------------------------------------------------------------
"""
change!(dgt::AbstractVector{<:Integer}, sites::AbstractVector{<:Integer}, ind::Integer; base::Integer=2)
Change the sub-digits to that with the target index.
This method is the inverse of `index`.
"""
@inline function change!(dgt::AbstractVector{T}, sites::AbstractVector{<:Integer}, ind::Integer; base::T=2) where T
N = ind - one(T)
for i = length(sites):-1:1
N, dgt[sites[i]] = divrem(N, base)
end
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 3038 | #-------------------------------------------------------------------------------------------------------------------------
# Flip
#-------------------------------------------------------------------------------------------------------------------------
export FlipBasis
"""
FlipBasis
Basis with translational and reflection symmetries.
"""
struct FlipBasis{Ti <: Integer} <: AbstractPermuteBasis
dgt::Vector{Ti} # Digits
I::Vector{Ti} # Representing states
R::Vector{Float64} # Normalization
P::Int # {±1}, parity
M::Int # base^length + 1
B::Ti # Base
end
#-------------------------------------------------------------------------------------------------------------------------
struct FlipJudge{T}
F # Projective selection
P::Int64 # Parity
B::T # Base
MAX::Int # base^length + 1
C::Float64 # Value sqrt(2)
end
#-------------------------------------------------------------------------------------------------------------------------
function (judge::FlipJudge)(dgt::AbstractVector{<:Integer}, i::Integer)
# If there is a projective selection function F, check `F(dgt)` first
isnothing(judge.F) || judge.F(dgt) || return (false, 0.0)
# Check parity
In = judge.MAX - i
In < i && return (false, 0.0)
if isequal(In, i)
isone(judge.P) || return (false, 0.0)
true, 2.0
else
true, judge.C
end
end
#-------------------------------------------------------------------------------------------------------------------------
function FlipBasis(
dtype::DataType=Int64; L::Integer, f=nothing, p::Integer, N::Union{Nothing, Integer}=nothing,
base::Integer=2, alloc::Integer=1000, threaded::Bool=true, small_N::Bool=true
)
@assert isone(p) || isone(-p) "Invalid parity"
@assert isnothing(N) || isequal(2N, L*(base-1)) "N = $N not compatible."
base = convert(dtype, base)
MAX = base ^ L + 1
I, R = begin
judge = if small_N || isnothing(N)
FlipJudge(f, p, base, MAX, sqrt(2))
else
num = L*(base-1)-N
g = isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
FlipJudge(g, p, base, MAX, sqrt(2))
end
if small_N && !isnothing(N)
selectindexnorm_N(judge, L, N, base=base)
else
threaded ? selectindexnorm_threaded(judge, L, base=base, alloc=alloc) : selectindexnorm(judge, L, 1:base^L, base=base, alloc=alloc)
end
end
FlipBasis(zeros(dtype, L), I, R, p, MAX, base)
end
#-------------------------------------------------------------------------------------------------------------------------
function index(b::FlipBasis)
Ia = index(b.dgt, base=b.B)
Ib = b.M - Ia
i, n = if Ib < Ia
binary_search(b.I, Ib), b.P
else
binary_search(b.I, Ia), 1
end
iszero(i) && return (zero(eltype(b)), one(i))
n * b.R[i], i
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 3011 | #-------------------------------------------------------------------------------------------------------------------------
# Parity
#-------------------------------------------------------------------------------------------------------------------------
export ParityBasis
"""
ParityBasis
Basis with translational and reflection symmetries.
Properties:
-----------
- dgt: Digits.
- I : Representing states.
- R : Normalization.
- P : {±1}, parity.
- B : Base.
"""
struct ParityBasis{Ti <: Integer} <: AbstractPermuteBasis
dgt::Vector{Ti} # Digits
I::Vector{Ti} # Representing states
R::Vector{Float64} # Normalization
P::Int # {±1}, parity
B::Ti # Base
end
#-------------------------------------------------------------------------------------------------------------------------
struct ParityJudge{T}
F # Projective selection
P::Int64 # Parity
B::T # Base
C::Float64 # Value sqrt(2).
end
#-------------------------------------------------------------------------------------------------------------------------
function (judge::ParityJudge)(dgt::AbstractVector{<:Integer}, i::Integer)
# If there is a projective selection function F, check `F(dgt)` first
isnothing(judge.F) || judge.F(dgt) || return (false, 0.0)
# Check parity
In = rindex(dgt, base=judge.B)
In < i && return (false, 0.0)
if isequal(In, i)
isone(judge.P) || return (false, 0.0)
true, 2.0
else
true, judge.C
end
end
#-------------------------------------------------------------------------------------------------------------------------
function ParityBasis(
dtype::DataType=Int64; L::Integer, f=nothing, p::Integer, N::Union{Nothing, Integer}=nothing,
base::Integer=2, alloc::Integer=1000, threaded::Bool=true, small_N::Bool=true
)
@assert isone(p) || isone(-p) "Invalid parity"
base = convert(dtype, base)
I, R = begin
judge = if small_N || isnothing(N)
ParityJudge(f, p, base, sqrt(2))
else
num = L*(base-1)-N
g = isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
ParityJudge(g, p, base, sqrt(2))
end
if small_N && !isnothing(N)
selectindexnorm_N(judge, L, N, base=base)
else
threaded ? selectindexnorm_threaded(judge, L, base=base, alloc=alloc) : selectindexnorm(judge, L, 1:base^L, base=base, alloc=alloc)
end
end
ParityBasis(zeros(dtype, L), I, R, p, base)
end
#-------------------------------------------------------------------------------------------------------------------------
function index(b::ParityBasis)
Ia = index(b.dgt, base=b.B)
Ib = rindex(b.dgt, base=b.B)
i, n = if Ib < Ia
binary_search(b.I, Ib), b.P
else
binary_search(b.I, Ia), 1
end
iszero(i) && return (zero(eltype(b)), one(i))
n * b.R[i], i
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 3939 | #-------------------------------------------------------------------------------------------------------------------------
# Parity + Flip
#-------------------------------------------------------------------------------------------------------------------------
export ParityFlipBasis
"""
FlipBasis
Basis with translational and reflection symmetries.
"""
struct ParityFlipBasis{Ti <: Integer} <: AbstractPermuteBasis
dgt::Vector{Ti} # Digits
I::Vector{Ti} # Representing states
R::Vector{Float64} # Normalization
P::Int # {±1}, parity
Z::Int # {±1}, spin-flip parity
M::Int # base^length + 1
B::Ti # Base
end
#-------------------------------------------------------------------------------------------------------------------------
struct ParityFlipJudge{T}
F # Projective selection
P::Int64 # Parity
Z::Int64 # Spin-flip parity
B::T # Base
MAX::Int # base^length + 1
C::Vector{Float64} # [2, 2sqrt(2), 0, 4]
end
#-------------------------------------------------------------------------------------------------------------------------
function double_parity_check(dgt, i, base, max, p, z)
(Ip = rindex(dgt, base=base)) < i && return (false, 1)
(Iz = max - i) < i && return (false, 3)
(Ipz = max - Ip) < i && return (false, 3)
N = 1
if isequal(Ip, i)
isone(p) || return (false, 3)
N += 1
end
if isequal(Iz, i)
isone(z) || return (false, 3)
N += 1
end
if isequal(Ipz, i)
isone(p*z) || return (false, 3)
N += 1
end
true, N
end
#-------------------------------------------------------------------------------------------------------------------------
function (judge::ParityFlipJudge)(dgt::AbstractVector{<:Integer}, i::Integer)
# If there is a projective selection function F, check `F(dgt)` first
isnothing(judge.F) || judge.F(dgt) || return (false, 0.0)
Q, n = double_parity_check(dgt, i, judge.B, judge.MAX, judge.P, judge.Z)
Q, judge.C[n]
end
#-------------------------------------------------------------------------------------------------------------------------
function ParityFlipBasis(
dtype::DataType=Int64; L::Integer, f=nothing, p::Integer, z::Integer, N::Union{Nothing, Integer}=nothing,
base::Integer=2, alloc::Integer=1000, threaded::Bool=true, small_N::Bool=true
)
@assert isone(p) || isone(-p) "Invalid parity"
@assert isnothing(N) || isequal(2N, L*(base-1)) "N = $N not compatible."
base = convert(dtype, base)
MAX = base ^ L + 1
I, R = begin
C = [2.0, 2*sqrt(2), 0.0, 4.0]
judge = if small_N || isnothing(N)
ParityFlipJudge(f, p, z, base, MAX, C)
else
num = L*(base-1)-N
g = isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
ParityFlipJudge(g, p, z, base, MAX, C)
end
if small_N && !isnothing(N)
selectindexnorm_N(judge, L, N, base=base)
else
threaded ? selectindexnorm_threaded(judge, L, base=base, alloc=alloc) : selectindexnorm(judge, L, 1:base^L, base=base, alloc=alloc)
end
end
ParityFlipBasis(zeros(dtype, L), I, R, p, z, MAX, base)
end
#-------------------------------------------------------------------------------------------------------------------------
function index(b::ParityFlipBasis)
I0 = index(b.dgt, base=b.B)
Ip = rindex(b.dgt, base=b.B)
Iz = b.M - I0
Ipz = b.M - Ip
Ir = min(I0, Iz, Ip, Ipz)
i = binary_search(b.I, Ir)
iszero(i) && return (0.0, one(b.B))
N = if isequal(Ir, I0)
b.R[i]
elseif isequal(Ir, Ip)
b.P * b.R[i]
elseif isequal(Ir, Iz)
b.Z * b.R[i]
else
b.P * b.Z * b.R[i]
end
N, i
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6465 | export ProjectedBasis
"""
ProjectedBasis{Ti}
Basis for subspace that is spanned only by product states.
It is basically like the `TensorBasis`, but contains only a subset of all basis vectors, selected by a given function.
Properties:
-----------
- `dgt`: Digits.
- `I` : List of indicies.
- `B` : Base.
"""
struct ProjectedBasis{T <: Integer} <: AbstractOnsiteBasis
dgt::Vector{T}
I::Vector{T}
B::T
end
#-------------------------------------------------------------------------------------------------------------------------
"""
Deep copy digits.
"""
copy(b::ProjectedBasis) = ProjectedBasis(deepcopy(b.dgt), b.I, b.B)
#-------------------------------------------------------------------------------------------------------------------------
function index(b::ProjectedBasis; check::Bool=true)
i = index(b.dgt, base=b.B)
ind = binary_search(b.I, i)
ind > 0 && return 1, ind
check ? error("No such symmetry.") : return zero(eltype(b)), one(ind)
end
#-------------------------------------------------------------------------------------------------------------------------
# Select basis vectors
#-------------------------------------------------------------------------------------------------------------------------
"""
binary_search(list::AbstractVector{<:Integer}, i<:Integer)
Return the position of i in a sorted list using binary search algorithm.
"""
function binary_search(list::AbstractVector{<:Integer}, i::Integer)
l::Int = 1
r::Int = length(list)
c::Int = (l + r) ÷ 2
while true
t = list[c]
(i < t) ? (r = c - 1) : (i > t) ? (l = c + 1) : break
(l > r) ? (c = 0; break) : (c = (l + r) ÷ 2)
end
c
end
#-------------------------------------------------------------------------------------------------------------------------
# Construction
#-------------------------------------------------------------------------------------------------------------------------
"""
dividerange(maxnum::Integer, nthreads::Integer)
Divide the interation range equally according to the number of threads.
Inputs:
-------
- `maxnum` : Maximum number of range.
- `nthreads`: Number of threads.
Outputs:
--------
- `list`: List of ranges.
"""
function dividerange(maxnum::T, nthreads::Integer) where T <: Integer
list = Vector{UnitRange{T}}(undef, nthreads)
eachthreads, left = divrem(maxnum, nthreads)
start = 1
for i = 1:left
stop = start + eachthreads
list[i] = start:stop
start = stop+1
end
for i = left+1:nthreads-1
stop = start + eachthreads - 1
list[i] = start:stop
start = stop+1
end
list[nthreads] = start:maxnum
list
end
#-------------------------------------------------------------------------------------------------------------------------
"""
selectindex(f, L, rg; base=2, alloc=1000)
Select the legal indices for a basis.
Inputs:
-------
- `f` : Function for digits that tells whether a digits is valid.
- `L` : Length of the system.
- `rg` : Range of interation.
- `base` : (Optional) Base, `base=2` by default.
- `alloc`: (Optional) Pre-allocation memory for the list of indices, `alloc=1000` by default.
Outputs:
--------
- `I`: List of indices in a basis.
"""
function selectindex(f, L::Integer, rg::UnitRange{T}; base::Integer=2, alloc::Integer=1000) where T <: Integer
dgt = zeros(T, L)
I = T[]
sizehint!(I, alloc)
for i in rg
change!(dgt, i, base=base)
f(dgt) && append!(I, i)
end
I
end
#-------------------------------------------------------------------------------------------------------------------------
"""
selectindex_threaded(f, L, rg; base=2, alloc=1000)
Select the legal indices with multi-threads.
Inputs:
-------
- `f` : Function for digits that tells whether a digits is valid as well as its normalization.
- `L` : Length of the system.
- `base` : (Optional) Base, `base=2` by default.
- `alloc`: (Optional) Pre-allocation memory for the list of indices, `alloc=1000` by default.
Outputs:
--------
- `I`: List of indices in a basis.
"""
function selectindex_threaded(f, L::Integer; base::T=2, alloc::Integer=1000) where T <: Integer
nt = Threads.nthreads()
ni = dividerange(base^L, nt)
nI = Vector{Vector{T}}(undef, nt)
Threads.@threads for ti in 1:nt
nI[ti] = selectindex(f, L, ni[ti], base=base, alloc=alloc)
end
I = vcat(nI...)
I
end
#-------------------------------------------------------------------------------------------------------------------------
function selectindex_N(f, L::Integer, N::Integer; base::T=2, alloc::Integer=1000, sorted::Bool=true) where T <: Integer
I = T[]
sizehint!(I, alloc)
for fdgt in multiexponents(L, N)
all(b < base for b in fdgt) || continue
dgt = (base-1) .- fdgt
isnothing(f) || f(dgt) || continue
ind = index(dgt, base=base)
append!(I, ind)
end
sorted ? sort(I) : I
end
#-------------------------------------------------------------------------------------------------------------------------
"""
ProjectedBasis(;L, N, base=2, alloc=1000, threaded=true)
Construction method for `ProjectedBasis` with fixed particle number (or total U(1) charge).
Inputs:
-------
- `dtype` : Data type for indices.
- `L` : Length of the system.
- `N` : Quantum number of up spins / particle number / U(1) charge.
- `base` : Base, default = 2.
- `alloc` : Size of the prealloc memory for the basis content, used only in multithreading, default = 1000.
- `threaded`: Whether use the multithreading, default = true.
- `small_N` : Whether use the small-N algorithm.
Outputs:
--------
- `b` : ProjectedBasis.
"""
function ProjectedBasis(dtype::DataType=Int64;
L::Integer, f=nothing, N::Union{Nothing, Integer}=nothing,
base::Integer=2, alloc::Integer=1000,
threaded::Bool=true, small_N::Bool=false
)
base = convert(dtype, base)
I = if isnothing(N)
threaded ? selectindex_threaded(f, L, base=base, alloc=alloc) : selectindex(f, L, 1:base^L, base=base, alloc=alloc)
elseif small_N
selectindex_N(f, L, N, base=base)
else
num = L * (base-1) - N
g = isnothing(f) ? x -> sum(x) == num : x -> (sum(x) == num && f(x))
threaded ? selectindex_threaded(g, L, base=base, alloc=alloc) : selectindex(g, L, 1:base^L, base=base, alloc=alloc)
end
ProjectedBasis(zeros(dtype, L), I, base)
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 9562 | export TranslationalBasis
"""
TranslationalBasis
Basis for subspace that is spanned by momentum states, which can also incorporate projected restriction.
For each basis vector represented by `dgt`, the vector is
|aₙ⟩ = ∑ᵢ Tⁱ |dgt⟩.
The normalized basis is
|n⟩ = Rₙ⁻¹ |aₙ⟩,
where Rₙ is the normalization.
Properties:
-----------
- `dgt`: Digits.
- `I` : List of indicies.
- `R` : List of normalization.
- `C` : Unit phase factor.
- `B` : Base.
"""
struct TranslationalBasis{Ti <: Integer, T <: Number} <: AbstractPermuteBasis
dgt::Vector{Ti}
I::Vector{Ti}
R::Vector{Float64}
C::Vector{T}
A::Int64
B::Ti
end
#-------------------------------------------------------------------------------------------------------------------------
eltype(::TranslationalBasis{Ti, T}) where {Ti, T} = T
copy(b::TranslationalBasis) = TranslationalBasis(deepcopy(b.dgt), b.I, b.R, b.C, b.A, b.B)
ncycle(b) = length(b.dgt) ÷ b.A
#-------------------------------------------------------------------------------------------------------------------------
# Functions selecting the basis
#-------------------------------------------------------------------------------------------------------------------------
"""
TranslationJudge
Structure used for selecting the basis contents.
Properties:
-----------
- F: Projective selection
- K: Momentum
- A: Length of unit cell
- B: Base
- C: Normalization coefficient
"""
struct TranslationJudge{T}
F # Projective selection
K::Int # Momentum
A::Int # Length of unit cell
L::Int # Length of translation
B::T # Base
C::Vector{Float64} # Normalization coefficient
end
#-------------------------------------------------------------------------------------------------------------------------
@inline check_momentum(n::Integer, k::Integer, L::Integer) = iszero(mod(n * k , L))
"""
(::TranslationJudge)(dgt, i)
Select basis and return normalization.
"""
function (judge::TranslationJudge)(dgt::AbstractVector{<:Integer}, i::Integer)
# If there is a projective selection function F, check `F(dgt)` first
isnothing(judge.F) || judge.F(dgt) || return (false, 0.0)
# Check translation
for n in 1:judge.L-1
circshift!(dgt, judge.A)
In = index(dgt, base=judge.B)
if In < i
# Find smaller indices, return false.
return (false, 0.0)
elseif isequal(In, i)
# Find periodicity; check if momentum is compatible
check_momentum(n, judge.K, judge.L) || return (false, 0.0)
return (true, judge.C[n])
end
end
# Finish a cycle
true, judge.C[judge.L]
end
#-------------------------------------------------------------------------------------------------------------------------
# Construction
#-------------------------------------------------------------------------------------------------------------------------
"""
selectindexnorm(f, L, rg; base=2, alloc=1000)
Select the legal indices and corresponding norm for a basis.
Inputs:
-------
- `f` : Function for digits that tells whether a digits is valid as well as its normalization.
- `L` : Length of the system.
- `rg` : Range of interation.
- `base` : (Optional) Base, `base=2` by default.
- `alloc`: (Optional) Pre-allocation memory for the list of indices, `alloc=1000` by default.
Outputs:
--------
- `I`: List of indices in a basis.
- `R`: List of normalization for each states.
"""
function selectindexnorm(f, L::Integer, rg::UnitRange{T}; base::Integer=2, alloc::Integer=1000) where T <: Integer
dgt = zeros(T, L)
I, R = T[], Float64[]
sizehint!(I, alloc)
sizehint!(R, alloc)
for i in rg
change!(dgt, i, base=base)
Q, N = f(dgt, i)
Q || continue
append!(I, i)
append!(R, N)
end
I, R
end
#-------------------------------------------------------------------------------------------------------------------------
function selectindexnorm_N(f, L::Integer, N::Integer; base::T=2, alloc::Integer=1000, sorted::Bool=true) where T <: Integer
I, R = T[], Float64[]
sizehint!(I, alloc)
sizehint!(R, alloc)
for fdgt in multiexponents(L, N)
all(b < base for b in fdgt) || continue
dgt = (base-1) .- fdgt
i = index(dgt, base=base)
Q, N = f(dgt, i)
Q || continue
append!(I, i)
append!(R, N)
end
sorted || return I, R
sperm = sortperm(I)
I[sperm], R[sperm]
end
#-------------------------------------------------------------------------------------------------------------------------
"""
selectindexnorm_threaded(f, L, rg; base=2, alloc=1000)
Select the legal indices and corresponding norm for a basis with multi-threads.
Inputs:
-------
- `f` : Function for digits that tells whether a digits is valid as well as its normalization.
- `L` : Length of the system.
- `base` : (Optional) Base, `base=2` by default.
- `alloc`: (Optional) Pre-allocation memory for the list of indices, `alloc=1000` by default.
Outputs:
--------
- `I`: List of indices in a basis.
- `R`: List of normalization for each states.
"""
function selectindexnorm_threaded(f, L::Integer; base::T=2, alloc::Integer=1000) where T <: Integer
nt = Threads.nthreads()
ni = dividerange(base^L, nt)
nI = Vector{Vector{T}}(undef, nt)
nR = Vector{Vector{Float64}}(undef, nt)
Threads.@threads for ti in 1:nt
nI[ti], nR[ti] = selectindexnorm(f, L, ni[ti], base=base, alloc=alloc)
end
I, R = vcat(nI...), vcat(nR...)
I, R
end
#-------------------------------------------------------------------------------------------------------------------------
"""
TranslationalBasis(f, k, L; base=2, alloc=1000, threaded=true)
Construction for `TranslationalBasis`.
Inputs:
-------
- `dtype` : Data type of index.
- `L` : Length of the system.
- `f` : Selection function for the basis contents.
- `k` : Momentum number from 0 to L-1.
- `N` : Particle number.
- `a` : Length of unit cell.
- `base` : Base, default = 2.
- `alloc` : Size of the prealloc memory for the basis content, used only in multithreading, default = 1000.
- `threaded`: Whether use the multithreading, default = true.
Outputs:
--------
- `b`: TranslationalBasis.
"""
function TranslationalBasis(dtype::DataType=Int64;
L::Integer, f=nothing, k::Integer=0, N::Union{Nothing, Integer}=nothing, a::Integer=1,
base::Integer=2, alloc::Integer=1000, threaded::Bool=true, small_N::Bool=false
)
len, check_a = divrem(L, a)
@assert iszero(check_a) "Length of unit-cell $a incompatible with L=$L"
#=
Change of definition:
old: T|k⟩ = exp(+ik)|k⟩,
new: T|k⟩ = exp(-ik)|k⟩.
In the new definition, cₖ⁺|VAC⟩ = |k⟩.
=#
k = mod(-k, len)
base = convert(dtype, base)
I, R = begin
norm = [len/sqrt(i) for i = 1:len]
judge = if small_N || isnothing(N)
TranslationJudge(f, k, a, len, base, norm)
else
num = L*(base-1)-N
g = isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
TranslationJudge(g, k, a, len, base, norm)
end
if small_N && !isnothing(N)
selectindexnorm_N(judge, L, N, base=base)
else
threaded ? selectindexnorm_threaded(judge, L, base=base, alloc=alloc) : selectindexnorm(judge, L, 1:base^L, base=base, alloc=alloc)
end
end
C = phase_factor(k, len)
TranslationalBasis(zeros(dtype, L), I, R, C, a, base)
end
#-------------------------------------------------------------------------------------------------------------------------
function phase_factor(k::Integer, len::Integer)
if iszero(k)
fill(1.0, len)
elseif isequal(2k, len)
[iseven(i) ? 1.0 : -1.0 for i=0:len-1]
else
[exp(-1im * 2π/len * k*i) for i=0:len-1]
end
end
#-------------------------------------------------------------------------------------------------------------------------
# Indexing
#-------------------------------------------------------------------------------------------------------------------------
"""
index(b::TranslationalBasis)
Index of the state in `TranslationalBasis`, together with the normalization.
Outputs:
--------
- `N`: Normalization for the state `b.dgt`.
- `i`: Index for the state `b.dgt`.
Notes:
------
To calculate the index of a given digits, we first shift the digits to that of the minimum index, then search for the place in the basis.
Because of the restriction from the momentum, some state with zero normalization (which is not included in the basis) will appear.
To avoid exception in the matrix constructon of `Operation`, we allow the index to not in the basis content.
When this happend, we return index 1, and normalization 0, so it has no effect on the matrix being filled.
"""
function index(b::TranslationalBasis)
I0 = index(b.dgt, base=b.B)
Im, M = I0, 0
# Cycle digits
resetQ = true
for i in 1:ncycle(b)-1
circshift!(b.dgt, b.A)
In = index(b.dgt, base=b.B)
if isequal(In, I0)
resetQ = false
break
elseif In < Im
Im, M = In, i
end
end
resetQ && circshift!(b.dgt, b.A)
# Search for minimal index
i = binary_search(b.I, Im)
iszero(i) && return (zero(eltype(b)), one(b.B))
# Find normalization and return result
N = b.C[M+1] * b.R[i]
N, i
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6237 | export TranslationFlipBasis
"""
TranslationFlipBasis
Basis with translational and spin-flip symmetries.
"""
struct TranslationFlipBasis{Ti, T} <: AbstractTranslationalParityBasis
dgt::Vector{Ti} # Digits
I::Vector{Ti} # Representing states
R::Vector{Float64} # Normalization
C::Vector{T} # Momentum phase exp(-1im * 2π/L * K)
P::Int # {±1}, parity
A::Int # Length of unit cell
M::Int # MAX = base^length + 1
B::Ti # Base
end
#-------------------------------------------------------------------------------------------------------------------------
eltype(::TranslationFlipBasis{Ti, T}) where {Ti, T} = T
copy(b::TranslationFlipBasis) = TranslationFlipBasis(deepcopy(b.dgt), b.I, b.R, b.C, b.P, b.A, b.B)
#-------------------------------------------------------------------------------------------------------------------------
# Functions selecting the basis
#-------------------------------------------------------------------------------------------------------------------------
struct TranslationFlipJudge{T <: Integer}
F # Projective selection
K::Int64 # Momentum
A::Int64 # Length of unit cell
P::Int64 # Parity eigenvalue {±1}
L::Int64 # Length of translation
B::T # Base
C::Vector{Float64} # Normalization coefficients
MAX::Int # Base^length + 1
end
#-------------------------------------------------------------------------------------------------------------------------
function (judge::TranslationFlipJudge)(dgt::AbstractVector{<:Integer}, i::Integer)
# First check projective selection rule
isnothing(judge.F) || judge.F(dgt) || return (false, 0.0)
R = judge.L
Qp = false
# Check Flip
In = judge.MAX - i
if In < i
return (false, 0.0)
elseif isequal(In, i)
Qp = true
# Check parity
isone(judge.P) || return (false, 0.0)
end
# Cycle digits
for n in 1:judge.L-1
circshift!(dgt, judge.A)
In1 = index(dgt, base=judge.B)
In2 = judge.MAX - In1
# Check cycled index
In1 < i && return (false, 0.0)
In2 < i && return (false, 0.0)
if isequal(In2, i)
# Check flip parity
isequal(isone(judge.P), iseven(div(n * judge.K, judge.L÷2))) || return (false, 0.0)
Qp = true
end
if isequal(In1, i)
# Find periodicity; check Momentum
iszero(mod(n * judge.K , judge.L)) || return (false, 0.0)
R = n
break
end
end
# Calculating norm
N = Qp ? judge.C[judge.L+R] : judge.C[R]
true, N
end
#-------------------------------------------------------------------------------------------------------------------------
# Construction
#-------------------------------------------------------------------------------------------------------------------------
"""
TranslationFlipBasis(f, k, p, L; base=2, alloc=1000, threaded=true)
Construction for `TranslationFlipBasis`.
Inputs:
-------
- `f` : Selection function for the basis contents.
- `k` : Momentum number from 0 to L-1.
- `p` : Parity number (under spin flip) ±1.
- `L` : Length of the system.
- `base` : Base, default = 2.
- `alloc` : Size of the prealloc memory for the basis content, used only in multithreading, default = 1000.
- `threaded`: Whether use the multithreading, default = true.
Outputs:
--------
- `b`: TranslationFlipBasis.
"""
function TranslationFlipBasis(
dtype::DataType=Int64; f=x->true, k::Integer=0, p::Integer=1, L::Integer, N::Union{Nothing, Integer}=nothing,
a::Integer=1, base::Integer=2, alloc::Integer=1000, threaded::Bool=false, small_N::Bool=false
)
len, check_a = divrem(L, a)
@assert iszero(check_a) "Length of unit-cell $a incompatible with L=$L"
@assert isone(p) || isone(-p) "Invalid parity"
@assert isnothing(N) || isequal(2N, L*(base-1)) "N = $N not compatible."
#=
Change of definition:
old: T|k⟩ = exp(+ik)|k⟩,
new: T|k⟩ = exp(-ik)|k⟩.
In the new definition, cₖ⁺|VAC⟩ = |k⟩.
=#
k = mod(-k, len)
base = convert(dtype, base)
MAX = base ^ L + 1
I, R = begin
N2 = [2len/ sqrt(i) for i = 1:len]
N1 = N2 ./ sqrt(2)
judge = if small_N || isnothing(N)
TranslationFlipJudge(f, k, a, p, len, base, vcat(N1, N2), MAX)
else
num = L*(base-1)÷2
g = isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
TranslationFlipJudge(g, k, a, p, len, base, vcat(N1, N2), MAX)
end
if small_N && !isnothing(N)
selectindexnorm_N(judge, L, N, base=base)
else
threaded ? selectindexnorm_threaded(judge, L, base=base, alloc=alloc) : selectindexnorm(judge, L, 1:base^L, base=base, alloc=alloc)
end
end
C = phase_factor(k, len)
TranslationFlipBasis(zeros(dtype, L), I, R, C, p, a, MAX, base)
end
#-------------------------------------------------------------------------------------------------------------------------
# Indexing
#-------------------------------------------------------------------------------------------------------------------------
"""
Return normalization and index.
"""
function index(b::TranslationFlipBasis)
Ia0 = index(b.dgt, base=b.B)
Ib0 = b.M - Ia0
Iam, Ibm = Ia0, Ib0
R, M = 0, 0
# Cycling and find monimum
resetQ = true
for i in 1:ncycle(b)-1
circshift!(b.dgt, b.A)
Ia1 = index(b.dgt, base=b.B)
if isequal(Ia1, Ia0)
resetQ = false
break
elseif Ia1 < Iam
Iam, R = Ia1, i
end
Ib1 = b.M - Ia1
if Ib1 < Ibm
Ibm, M = Ib1, i
end
end
resetQ && circshift!(b.dgt, b.A)
# Find index and normalization
i, n = if Ibm < Iam
binary_search(b.I, Ibm), b.P * b.C[M+1]
else
binary_search(b.I, Iam), b.C[R+1]
end
iszero(i) && return (zero(eltype(b)), one(eltype(b.I)))
n * b.R[i], i
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6876 | #-------------------------------------------------------------------------------------------------------------------------
# Translation + Parity
#-------------------------------------------------------------------------------------------------------------------------
export TranslationParityBasis
"""
TranslationParityBasis
Basis with translational and reflection symmetries.
Properties:
-----------
- dgt: Digits.
- I : Representing states.
- R : Normalization.
- C : {±1}, momentum phase.
- P : {±1}, parity.
- A : Length of unit cell.
- B : Base.
"""
struct TranslationParityBasis{Ti <: Integer} <: AbstractTranslationalParityBasis
dgt::Vector{Ti} # Digits
I::Vector{Ti} # Representing states
R::Vector{Float64} # Normalization
C::Vector{Int} # Momentum phase exp(1im * 0/π) = {±1}
P::Int # {±1}, parity
A::Int # Length of unit cell
B::Ti # Base
end
#-------------------------------------------------------------------------------------------------------------------------
eltype(::TranslationParityBasis) = Float64
copy(b::TranslationParityBasis) = TranslationParityBasis(deepcopy(b.dgt), b.I, b.R, b.C, b.P, b.A, b.B)
#-------------------------------------------------------------------------------------------------------------------------
# Functions selecting the basis
#-------------------------------------------------------------------------------------------------------------------------
function rindex(dgt::AbstractVector{<:Integer}; base::T) where T <: Integer
evalpoly(base, dgt) + one(T)
end
#-------------------------------------------------------------------------------------------------------------------------
struct TranslationParityJudge{T <: Integer}
F # Projective selection
K::Int64 # Momentum phase exp(1im * 0/π) = {±1}
A::Int64 # Length of unit cell
P::Int64 # Parity eigenvalue {±1}
L::Int64 # Length of translation
B::T # Base
C::Vector{Float64} # Normalization coefficients
end
#-------------------------------------------------------------------------------------------------------------------------
function (judge::TranslationParityJudge)(dgt::AbstractVector{<:Integer}, i::Integer)
# First check projective selection rule
isnothing(judge.F) || judge.F(dgt) || return (false, 0.0)
R = judge.L
Qp = false
# Check reflection
In = rindex(dgt, base=judge.B)
if In < i
return (false, 0.0)
elseif isequal(In, i)
Qp = true
# Check parity
isone(judge.P) || return (false, 0.0)
end
# Cycle digits
for n in 1:judge.L-1
circshift!(dgt, judge.A)
In1 = index(dgt, base=judge.B)
In2 = rindex(dgt, base=judge.B)
# Check cycled index
In1 < i && return (false, 0.0)
In2 < i && return (false, 0.0)
if isequal(In2, i)
# Check Parity
isone(judge.P * judge.K ^ n) || return (false, 0.0)
Qp = true
end
if isequal(In1, i)
# Find periodicity; check Momentum
isone(judge.K) || iseven(n) || return (false, 0.0)
R = n
break
end
end
# Calculating norm
N = Qp ? judge.C[judge.L+R] : judge.C[R]
true, N
end
#-------------------------------------------------------------------------------------------------------------------------
# Construction
#-------------------------------------------------------------------------------------------------------------------------
"""
TranslationParityBasis(f, k, p, L; base=2, alloc=1000, threaded=true)
Construction for `TranslationParityBasis`.
Inputs:
-------
- `f` : Selection function for the basis contents.
- `k` : Momentum number, 0 or L/2.
- `p` : Parity number ±1.
- `L` : Length of the system.
- `N` : Particle numper.
- `a` : Length of unit cell.
- `base` : Base, default = 2.
- `alloc` : Size of the prealloc memory for the basis content, used only in multithreading, default = 1000.
- `threaded`: Whether use the multithreading, default = true.
Outputs:
--------
- `b`: TranslationParityBasis.
"""
function TranslationParityBasis(
dtype::DataType=Int64; L::Integer, f=nothing, k::Integer=0, p::Integer=1, N::Union{Nothing, Integer}=nothing,
a::Integer=1, base::Integer=2, alloc::Integer=1000, threaded::Bool=true, small_N::Bool=false
)
len, check_a = divrem(L, a)
@assert iszero(check_a) "Length of unit-cell $a incompatible with L=$L"
k = if iszero(mod(k, len))
1
elseif iszero(mod(2k, len))
-1
else
error("Momentum $k incompatible with parity.")
end
@assert isone(p) || isone(-p) "Invalid parity"
base = convert(dtype, base)
I, R = begin
N2 = [2len/ sqrt(i) for i = 1:len]
N1 = N2 ./ sqrt(2)
judge = if small_N || isnothing(N)
TranslationParityJudge(f, k, a, p, len, base, vcat(N1, N2))
else
num = L*(base-1)-N
g = isnothing(f) ? x -> (sum(x) == num) : x -> (sum(x) == num && f(x))
TranslationParityJudge(g, k, a, p, len, base, vcat(N1, N2))
end
if small_N && !isnothing(N)
selectindexnorm_N(judge, L, N, base=base)
else
threaded ? selectindexnorm_threaded(judge, L, base=base, alloc=alloc) : selectindexnorm(judge, L, 1:base^L, base=base, alloc=alloc)
end
end
C = isone(k) ? fill(1, len) : [iseven(i) ? 1 : -1 for i=0:len-1]
TranslationParityBasis(zeros(dtype, L), I, R, C, p, a, base)
end
#-------------------------------------------------------------------------------------------------------------------------
# Indexing
#-------------------------------------------------------------------------------------------------------------------------
"""
index(b::TranslationParityBasis)
Return normalization and index.
"""
function index(b::TranslationParityBasis)
Ia0 = index(b.dgt, base=b.B)
Ib0 = rindex(b.dgt, base=b.B)
Iam, Ibm = Ia0, Ib0
R, M = 0, 0
# Cycling and find monimum
resetQ = true
for i in 1:ncycle(b)-1
circshift!(b.dgt, b.A)
Ia1 = index(b.dgt, base=b.B)
if isequal(Ia1, Ia0)
resetQ = false
break
elseif Ia1 < Iam
Iam, R = Ia1, i
end
Ib1 = rindex(b.dgt, base=b.B)
if Ib1 < Ibm
Ibm, M = Ib1, i
end
end
resetQ && circshift!(b.dgt, b.A)
# Find index and normalization
i, n = if Ibm < Iam
binary_search(b.I, Ibm), b.P * b.C[M+1]
else
binary_search(b.I, Iam), b.C[R+1]
end
iszero(i) && return (zero(eltype(b)), one(eltype(b.I)))
n * b.R[i], i
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6533 | #=---------------------------------------------------------------------------------------------------
Conversion
Due to julia's column major convention, the conversion between tensor and vector is not straight-
forward. It is basically a reshape and permute indices.
---------------------------------------------------------------------------------------------------=#
"""
vec2tensor!(dest, v)
Convert vector `v` to tensor, with row-major convention.
Inputs:
-------
- dest: Tensor to write
- v : Vector
"""
function vec2tensor!(dest::Array, v::AbstractVector)
T = reshape(v, size(dest))
permutedims!(dest, T, ndims(dest):-1:1)
end
#----------------------------------------------------------------------------------------------------
"""
vec2tensor(v; base=2)
Convert vector `v` to tensor, with row-major convention.
"""
function vec2tensor(v::AbstractVector; base::Integer=2)
L = round(Int, log(base, length(v)))
@assert base^L == length(v) "Dimension not right."
T = Array{eltype(v), L}(undef, fill(base, L)...)
vec2tensor!(T, v)
end
#----------------------------------------------------------------------------------------------------
export mps2vec
"""
mps2vec(psi::MPS)
Convert MPS to a vector
"""
function mps2vec(psi::MPS)
v = ITensor(1.0)
for t in psi
v *= t
end
T = Array(v, reverse(siteinds(psi)))
reshape(T, :)
end
#----------------------------------------------------------------------------------------------------
"""
mps2vec(psi::MPS, B::AbstractBasis)
Convert MPS to a vector, with a given basis `B`.
"""
function mps2vec(psi::MPS, B::AbstractBasis)
L = length(psi)
s = siteinds(psi)
v = Vector{eltype(psi[1])}(undef, size(B, 1))
for i in eachindex(v)
R = change!(B, i)
val = ITensor(1.0)
for j in 1:L
val *= psi[j] * state(s[j], B.dgt[j]+1)
end
v[i] = scalar(val) * L / R
end
v
end
#----------------------------------------------------------------------------------------------------
export vec2mps
function vec2mps(v::AbstractVector, s::AbstractVector{<:Index})
T = vec2tensor(v; base=space(s[1]))
MPS(T, s)
end
#----------------------------------------------------------------------------------------------------
export mat2op
"""
Convert a matrix to an ITensor operator
"""
function mat2op(mat::AbstractMatrix, s::Index...)
L = length(s)
d = space(s[1])
T = reshape(mat, fill(d, 2L)...)
Tp = permutedims(T, [L:-1:1; 2L:-1:L+1])
op(Tp, s...)
end
#----------------------------------------------------------------------------------------------------
export op2mat
"""
Convert a ITensor operator to a matrix
"""
function op2mat(o::ITensor, s::Index...)
rs = reverse(s)
T = Array(o, adjoint.(rs), rs)
N = space(s[1]) ^ length(s)
reshape(T, N, N)
end
#=---------------------------------------------------------------------------------------------------
MPS constructions
---------------------------------------------------------------------------------------------------=#
export pbcmps
"""
pbcmps(sites, tensors)
Construct an MPS from a list of tensor.
"""
function pbcmps(
sites::AbstractVector,
tensors::AbstractVector{<:AbstractArray}
)
L = length(sites)
link = map(1:L-1) do i
χ = size(tensors[i], 2)
Index(χ, "Link,l=$i")
end
ltensor, rtensor = tensors[1], tensors[end]
χ = size(ltensor, 1)
ψ = MPS(L)
for i in 2:L-1
ψ[i] = ITensor(tensors[i], link[i-1], link[i], sites[i])
end
# Fix boundary |1⟩⟨1|
ψ[1] = ITensor(ltensor[1, :, :], link[1], sites[1])
ψ[L] = ITensor(rtensor[:, 1, :], link[L-1], sites[L])
res = deepcopy(ψ)
for n in 2:χ # Fix boundary |n⟩⟨n|
ψ[1] = ITensor(ltensor[n, :, :], link[1], sites[1])
ψ[L] = ITensor(rtensor[:, n, :], link[L-1], sites[L])
res += ψ
end
orthogonalize!(res, 1)
normalize!(res)
end
#----------------------------------------------------------------------------------------------------
export productstate
ITensors.state(s::Index, v::AbstractVector) = ITensor(v, s)
"""
productstate(s, states)
Return a product MPS
Inputs:
-------
- s : Vector of indices
- states: Vector of vector representing local states
"""
function productstate(s::AbstractVector{<:Index}, states::AbstractVector{<:AbstractVector})
L, d = length(s), length(states[1])
link = [Index(1, "Link,l=$i") for i in 1:L-1]
ψ = MPS(L)
ψ[1] = ITensor(reshape(states[1], d, 1), s[1], link[1])
ψ[L] = ITensor(reshape(states[L], d, 1), s[L], link[L-1])
for i in 2:L-1
ψ[i] = ITensor(reshape(states[i], d, 1, 1), s[i], link[i-1], link[i])
end
ψ
end
#=---------------------------------------------------------------------------------------------------
MPS properties
---------------------------------------------------------------------------------------------------=#
export ent_spec, ent_specs!, ent_S!
"""
ent_specs(ψ::MPS, b::Integer)
Return entanglement spectrum between site `b` and `b+1`.
Inputs:
-------
- ψ: MPS
- b: Link index
"""
function ent_specs(ψ::MPS, b::Integer)
ψ = orthogonalize(ψ, b)
isone(b) && return svd(ψ[b], siteind(ψ, b)).spec.eigs
svd(ψ[b], (linkind(ψ, b-1), siteind(ψ, b))).spec.eigs
end
#----------------------------------------------------------------------------------------------------
function ent_specs!(ψ::MPS, b::Integer)
orthogonalize!(ψ, b)
isone(b) && return svd(ψ[b], siteind(ψ, b)).spec.eigs
svd(ψ[b], (linkind(ψ, b-1), siteind(ψ, b))).spec.eigs
end
#----------------------------------------------------------------------------------------------------
"""
ent_S(ψ::MPS, b::Integer)
Return entanglement entropy between site `b` and `b+1`.
Inputs:
-------
- ψ: MPS
- b: Link index
"""
function ent_S(ψ::MPS, b::Integer)
spec = ent_specs(ψ, b)
entropy(spec)
end
#----------------------------------------------------------------------------------------------------
function ent_S!(ψ::MPS, b::Integer)
spec = ent_specs!(ψ, b)
entropy(spec)
end
#----------------------------------------------------------------------------------------------------
"""
ent_specs(ψ::MPS)
Return entanglement entropies.
Inputs:
-------
- ψ: MPS
Outputs:
--------
- S: Vector of entropy
"""
function ent_S(ψ::MPS)
L = length(ψ)
S = Vector{Float64}(undef, L)
ψ = orthogonalize(ψ, 1)
for i in 1:L
S[i] = ent_S!(ψ, i)
end
S
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 10918 | #---------------------------------------------------------------------------------------------------
const PAULI_CONVERSION = let T = zeros(ComplexF64, 4, 2, 2)
for i in 1:4
T[i, :, :] += conj.(PAULI[i]) / 2
end
T
end
#---------------------------------------------------------------------------------------------------
const PAULI_INV_CONV = let T = zeros(ComplexF64, 2, 2, 4)
for i in 1:4
T[:, :, i] += PAULI[i]
end
T
end
#---------------------------------------------------------------------------------------------------
export pauli
"""
pauli(i, L=1)
Return ith (size-L) Pauli matrices.
"""
function pauli(i::Integer, L::Integer=1)
inds = digits(i-1, base=4, pad=L) |> reverse!
σ(inds)
end
#---------------------------------------------------------------------------------------------------
"""
pauli(Is::AbstractVector{<:Real})
Return a matrix from Pauli coefficients
"""
function pauli(Is::AbstractVector{<:Real})
L = round(Integer, log(4, length(Is)))
@assert 4^L == length(Is)
out = zeros(ComplexF64, 2^L, 2^L)
for i in eachindex(Is)
out += Is[i] * pauli(i, L)
end
out
end
#---------------------------------------------------------------------------------------------------
"""
Compute tr(A * B), where A is a Pauli matrix.
"""
function pauli_mtr(A::SparseMatrixCSC, B::AbstractMatrix)
rows, vals = rowvals(A), nonzeros(A)
res = zero(promote_type(eltype(A), eltype(B)))
for j in axes(A, 2)
val, row = vals[j], rows[j]
res += val * B[j, row]
end
#res = tr(A * B)
res
end
#---------------------------------------------------------------------------------------------------
export pauli_list
"""
pauli_list(A)
Return pauli components of a 2×2 matrix `A`.
"""
function pauli_list(A::AbstractMatrix, T::DataType=Float64)
n = round(Integer, log(2, size(A, 1)))
N = 2^n
@assert N == size(A, 1) "dimension D = $(size(A, 1)) not right."
list = Vector{T}(undef, N^2)
for i in eachindex(list)
c = pauli_mtr(pauli(i, n), A) / N
list[i] = T <: Real ? real(c) : c
end
return list
end
#---------------------------------------------------------------------------------------------------
"""
pauli_op_mat(f)
Matrix representation for f(ρ).
"""
function pauli_op_mat(f, L::Integer=1)
N = 4^L
mat = Matrix{Float64}(undef, N, N)
for i in axes(mat, 2)
mat[:, i] = f(pauli(i, L)) |> pauli_list
end
return mat
end
#---------------------------------------------------------------------------------------------------
"""
dissipation(L,ρ)
Compute dissipation
D[L]ρ = L⋅ρ⋅L⁺ - 1/2{L⁺L,ρ}
"""
function dissipation(L::AbstractMatrix, ρ::AbstractMatrix)
Lρ = L * ρ
Ld = L'
LLρ = Ld * Lρ
return Lρ * Ld - (LLρ + LLρ') / 2
end
#---------------------------------------------------------------------------------------------------
"""
commutation(L,ρ)
Compute commutation
-i[H, ρ]
"""
function commutation(H::AbstractMatrix, ρ::AbstractMatrix)
Hρ = -1im * H * ρ
Hρ + Hρ'
end
#---------------------------------------------------------------------------------------------------
export dissipation_mat
"""
dissipation_mat(L)
Matrix representation for D[L].
"""
function dissipation_mat(L::AbstractMatrix)
n = round(Integer, log(2, size(L, 1)))
@assert 2^n == size(L, 1) "dimension D = $(size(L, 1)) not right."
f = ρ -> dissipation(L,ρ)
pauli_op_mat(f, n)
end
#---------------------------------------------------------------------------------------------------
export commutation_mat
"""
commutation_mat(L)
Matrix representation for -i[H,⋅].
"""
function commutation_mat(H::AbstractMatrix)
n = round(Integer, log(2, size(H, 1)))
@assert 2^n == size(H, 1) "dimension D = $(size(H, 1)) not right."
f = ρ -> commutation(H,ρ)
pauli_op_mat(f, n)
end
#---------------------------------------------------------------------------------------------------
# Define Pauli basis
#---------------------------------------------------------------------------------------------------
ITensors.space(::SiteType"Pauli") = 4
ITensors.state(::StateName"I", ::SiteType"Pauli") = [1, 0, 0, 0]
ITensors.state(::StateName"X", ::SiteType"Pauli") = [0, 1, 0, 0]
ITensors.state(::StateName"Y", ::SiteType"Pauli") = [0, 0, 1, 0]
ITensors.state(::StateName"Z", ::SiteType"Pauli") = [0, 0, 0, 1]
ITensors.state(::StateName"Up", ::SiteType"Pauli") = [1/2, 0, 0, 1/2]
ITensors.state(::StateName"Dn", ::SiteType"Pauli") = [1/2, 0, 0, -1/2]
#---------------------------------------------------------------------------------------------------
# MPS/MPO
#---------------------------------------------------------------------------------------------------
function _umat(n::Int64)
B1 = ParityBasis(L=2, p=1, base=n)
B2 = ParityBasis(L=2, p=-1, base=n)
n1, n2 = size(B1, 1), size(B2, 1)
out = zeros(ComplexF64, n^2, n^2)
for i in 1:n1
a = 1 / change!(B1, i)
out[index(B1.dgt; base=n), i] += a
reverse!(B1.dgt)
out[index(B1.dgt; base=n), i] += a
end
for i in 1:n2
j = n1 + i
b = 1im / change!(B2, i)
out[index(B2.dgt; base=n), j] += b
reverse!(B2.dgt)
out[index(B2.dgt; base=n), j] -= b
end
out
end
const lru_umat = LRU{Int64, Matrix{ComplexF64}}(maxsize=30)
function cached_umat(n::Int64)
get!(lru_umat, n) do
_umat(n)
end
end
#---------------------------------------------------------------------------------------------------
export mps2pmps
function mps2pmps(ψ::MPS, S::AbstractVector)
s = siteinds(ψ)
L = length(s)
psi = MPS(L)
psi[1] = begin
l1 = linkind(ψ, 1)
Cl = combiner(l1, l1')
C = ITensor(PAULI_CONVERSION, S[1], s[1]', s[1])
ψ[1]' * conj(ψ[1]) * C * Cl
end
for i in 2:L-1
li = linkind(ψ, i)
Cl2 = combiner(li, li')
C = ITensor(PAULI_CONVERSION, S[i], s[i]', s[i])
psi[i] = ψ[i]' * conj(ψ[i]) * C * Cl * Cl2
Cl = Cl2
end
psi[L] = begin
C = ITensor(PAULI_CONVERSION, S[L], s[L]', s[L])
ψ[L]' * conj(ψ[L]) * C * Cl
end
for i in 1:L-1
n = linkdim(ψ, i)
u = cached_umat(n)
l0 = commonind(psi[i], psi[i+1])
l = Index(n^2, tags="Link,l=$i")
U = ITensor(u, l0, l)
Ud = ITensor(u', l, l0)
psi[i] = psi[i] * U |> real
psi[i+1] = Ud * psi[i+1]
end
psi[L] = real(psi[L])
psi
end
#---------------------------------------------------------------------------------------------------
export pmps2mpo
"""
pmps2mpo(ψ, s)
Convert Pauli MPS to MPO.
"""
function pmps2mpo(ψ::MPS, s::AbstractVector)
L = length(s)
S = siteinds(ψ)
@assert length(ψ) == L
O = MPO(L)
for i in eachindex(s)
si = s[i]
C = ITensor(PAULI_INV_CONV, si', si, S[i])
O[i] = C * ψ[i]
end
O
end
#---------------------------------------------------------------------------------------------------
# Function on Pauli basis
#---------------------------------------------------------------------------------------------------
"""
Return the operator norm (N = |⟨I|ρ⟩|).
The renormed (ρ/N = I + ⋯) is the correct density matrix.
"""
function density_norm(ψ::MPS)
s = siteinds(ψ)
V = ITensor(1.0)
for j in eachindex(s)
V *= ψ[j] * state(s[j], 1)
end
scalar(V) |> abs
end
#---------------------------------------------------------------------------------------------------
function density_expect(ψ::MPS, o::Integer; normalize::Bool=true)
s = siteinds(ψ)
L = let V = ITensor(1.0)
l = Vector{ITensor}(undef, length(s)); l[1] = V
for j in 2:length(s)
V *= ψ[j-1] * state(s[j-1], 1)
l[j] = V
end
l
end
R = let V = ITensor(1.0)
l = Vector{ITensor}(undef, length(s)); l[end] = V
for j in length(s)-1:-1:1
V *= ψ[j+1] * state(s[j+1], 1)
l[j] = V
end
l
end
out = Vector{Float64}(undef, length(s))
for j in eachindex(s)
V = ψ[j] * state(s[j], o)
out[j] = L[j] * V * R[j] |> scalar |> real
end
if normalize
N = L[2]*R[1] |> scalar |> real
out ./= N
end
out
end
#---------------------------------------------------------------------------------------------------
function density_expect(ψ::MPS, h::AbstractMatrix)
n = round(Int, log(2, size(h, 1)))
hl = pauli_list(h)
s = siteinds(ψ)
L = let V = ITensor(1.0)
l = Vector{ITensor}(undef, length(s)); l[1] = V
for j in 2:length(s)
V *= ψ[j-1] * state(s[j-1], 1)
l[j] = V
end
l
end
R = let V = ITensor(1.0)
l = Vector{ITensor}(undef, length(s)); l[end] = V
for j in length(s)-1:-1:1
V *= ψ[j+1] * state(s[j+1], 1)
l[j] = V
end
l
end
out = Vector{Float64}(undef, length(s)-n+1)
for j in eachindex(out)
V = L[j]
for k in j:j+n-1
V = V * ψ[k]
end
V = V * R[j+n-1]
vec = Array(V, s[j+n-1:-1:j]...)
list = reshape(vec, :)
out[j] = dot(list, hl)
end
out
end
#---------------------------------------------------------------------------------------------------
# DAOE
#---------------------------------------------------------------------------------------------------
function fdaoe(s::AbstractVector, l::Integer, γ::Real)
L = length(s)
κ = exp(-2γ)
#=----------------------------------------------------------
Wᴵᴵ = I(l+1)⁺ ⊕ (∑|n⟩⟨n+1| + κ|l⟩⟨l|)⁻
Wᶻᶻ = (∑|n⟩⟨n+1| + κ|l+1⟩⟨l+1|)⁺ ⊕ I(l)⁻
Wˣˣ = Wʸʸ = [0 A; B 0], where
A = I(l)⁺⁻ + κ|l+1⟩⁺⟨l|⁻
B = ∑|n⟩⁺⟨n+1|⁻
----------------------------------------------------------=#
Wi = zeros(2l+1, 2l+1, 4, 4)
Wi[1:l+1, 1:l+1, 1, 1] = I(l+1)
Wi[l+2:end, l+2:end, 1, 1] = diagm(1 => ones(l-1))
Wi[end, end, 1, 1] = κ
Wi[1:l+1, 1:l+1, 4, 4] = diagm(1 => ones(l))
Wi[l+1, l+1, 4, 4] = κ
Wi[l+2:end, l+2:end, 4, 4] = I(l)
A = diagm(l+1, l, ones(l))
A[end, end] = κ
B = diagm(l, l+1, 1 => ones(l))
Wi[1:l+1, l+2:end, 2, 2] = A
Wi[1:l+1, l+2:end, 3, 3] = A
Wi[l+2:end, 1:l+1, 2, 2] = B
Wi[l+2:end, 1:l+1, 3, 3] = B
#=----------------------------------------------------------
L = ⟨1|
R = ∑ₙ|n⟩
----------------------------------------------------------=#
W1 = Wi[1,:,:,:]
WL = sum(Wi[:,i,:,:] for i in axes(Wi, 2))
links = [Index(2l+1, "Link,l=$i") for i in 1:L-1]
D = MPO(L)
D[1] = ITensor(W1, links[1], s[1]', s[1])
for i in 2:L-1
D[i] = ITensor(Wi, links[i-1], links[i], s[i]', s[i])
end
D[L] = ITensor(WL, links[L-1], s[L]', s[L])
D
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 2025 | #----------------------------------------------------------------------------------------------------
# TEBD
#----------------------------------------------------------------------------------------------------
export tebd_n!
"""
tebd_n!(ψ, G1, G2; cutoff=1e-14, maxdim=30)
n-site TEBD.
"""
function tebd_n!(ψ::MPS, G1::Vector, G2::Vector; cutoff::Real=1e-14, maxdim::Integer=30)
L = length(ψ)
s = siteinds(ψ)
n = length(inds(G1[1])) ÷ 2
orthogonalize!(ψ, 1)
#------------------------------------------------------------
# First block
block = ITensor(1.0)
for i in 1:n
block *= ψ[i]
end
wf = G1[1] * block |> noprime!
U, S, V = svd(wf, s[1]; cutoff, maxdim)
ψ[1], T = U, S * V
link = commonind(ψ[1], T)
#------------------------------------------------------------
# moving right
for i in 2:L-n
wf = G1[i] * (T * ψ[i+n-1]) |> noprime!
U, S, V = svd(wf, link, s[i]; cutoff, maxdim)
ψ[i], T = U, S * V
link = commonind(ψ[i], T)
end
#------------------------------------------------------------
# dealing with the last block
wf = apply(G2[1], G1[L-n+1]) * (T * ψ[L]) |> noprime!
U, S, V = svd(wf, link, s[L-n+1:L-1]...; cutoff, maxdim)
T, ψ[L] = U * S, V
#------------------------------------------------------------
# moving left
for j in 2:L-n
i = L-j-n+2
wf = G2[j] * (ψ[i] * T) |> noprime!
link = commonind(ψ[i-1], ψ[i])
U, S, V = svd(wf, commonind(ψ[i-1], ψ[i]), s[i:i+n-2]...; cutoff, maxdim)
T, ψ[i+n-1] = U * S, V
end
#------------------------------------------------------------
# dealing with the first block
wf = G2[L-n+1] * (ψ[1] * T) |> noprime!
for i in n:-1:2
U, S, V = svd(wf, s[1:i-1]...; cutoff, maxdim)
wf, ψ[i] = U * S, V
end
ψ[1] = wf
#------------------------------------------------------------
# restore gauge
ψ.llim = 0
ψ.rlim = 2
normalize!(ψ)
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 6646 | #---------------------------------------------------------------------------------------------------
# Many-body Lindblad Form
#---------------------------------------------------------------------------------------------------
export lindblad, densitymatrix, expectation
"""
Lindblad Equation:
∂ₜρ = -i[H, ρ] + ∑ᵢ LᵢρLᵢ⁺ - 1/2 ∑ᵢ {Lᵢ⁺Lᵢ, ρ}
The object `Lindblad` store the information of the supper operator.
"""
struct Lindblad{T1, T2}
H::Matrix{T1}
L::Vector{Matrix{T2}}
end
"""
Construction for `Lindblad`.
"""
lindblad(H, L) = Lindblad(Array(H), [Array(l) for l in L])
eltype(::Lindblad{T1, T2}) where {T1, T2} = promote_type(T1, T2)
#---------------------------------------------------------------------------------------------------
# Density Matrix
#---------------------------------------------------------------------------------------------------
"""
Density Matrix under Many-body Basis
"""
struct DensityMatrix{T}
ρ::Matrix{T}
end
#---------------------------------------------------------------------------------------------------
densitymatrix(ρ::AbstractArray) = DensityMatrix(ρ)
densitymatrix(ψ::AbstractVector) = DensityMatrix(ψ * ψ')
function densitymatrix(i::Integer, L::Integer; base::Integer=2)
N = base ^ L
ρ = zeros(N, N)
ρ[i, i] = 1
DensityMatrix(ρ)
end
#---------------------------------------------------------------------------------------------------
Array(dm::DensityMatrix) = Hermitian(dm.ρ)
"""
Normalize the density operator so that tr[ρ]=1.
"""
function LinearAlgebra.normalize!(dm::DenseMatrix)
dm.ρ ./= tr(dm.ρ)
end
#---------------------------------------------------------------------------------------------------
expectation(O::AbstractMatrix, dm::DensityMatrix) = tr(O * dm.ρ)
expectation(O::Hermitian, dm::DensityMatrix) = real(tr(O * dm.ρ))
#---------------------------------------------------------------------------------------------------
function entropy(dm::DensityMatrix; α::Real=1, cutoff::Real=1e-20)
λ = eigvals(Hermitian(dm.ρ))
entropy(λ, α=α, cutoff=cutoff)
end
#---------------------------------------------------------------------------------------------------
# Lindblad Evolution
#---------------------------------------------------------------------------------------------------
function *(lb::Lindblad, ρ::Matrix)
H, L = lb.H, lb.L
out = -1im * (H * ρ - ρ * H)
LdL = zeros(eltype(L[1]), size(L[1]))
for l in L
ld = l'
out += l * ρ * ld
LdL += ld * l
end
LdL ./= -2
out += LdL * ρ
out += ρ * LdL
out
end
#---------------------------------------------------------------------------------------------------
function (lb::Lindblad)(dm::DensityMatrix, dt::Real=0.05; order::Integer=5)
ρ = dm.ρ
mat = Array(ρ)
dρ = dt * (lb * ρ)
mat += dρ
for i = 2:order
dρ = (dt/i) * (lb * dρ)
mat += dρ
end
DensityMatrix(mat)
end
#---------------------------------------------------------------------------------------------------
# Single-body Lindblad Form
#---------------------------------------------------------------------------------------------------
export quadraticlindblad, covariancematrix,majoranaform, fermioncorrelation
struct QuardraticLindblad{T1 <: Real, T2 <: Real, T3 <: Real}
X::Matrix{T1}
Y::Matrix{T2}
Z::Vector{Matrix{T3}}
end
#---------------------------------------------------------------------------------------------------
function quadraticlindblad(
H::AbstractMatrix,
L::AbstractMatrix,
M::AbstractVector{<:AbstractMatrix}
)
B = L * L'
X = H - 2 * real(B) + 8 * sum(Ms^2 for Ms in M)
Y = 4 * imag(B)
Z = [4 * Ms for Ms in M]
QuardraticLindblad(X, Y, Z)
end
function quadraticlindblad(
H::AbstractMatrix,
L::AbstractMatrix
)
B = L * L'
X = H - 2 * real(B)
Y = 4 * imag(B)
Z = Matrix{Float64}[]
QuardraticLindblad(X, Y, Z)
end
#---------------------------------------------------------------------------------------------------
# Majorana Covariant Matrix
#---------------------------------------------------------------------------------------------------
struct CovarianceMatrix{T <: Real}
Γ::Matrix{T}
N::Integer
end
#---------------------------------------------------------------------------------------------------
function covariancematrix(Γ::AbstractMatrix{<:Real})
N = size(Γ, 1) ÷ 2
CovarianceMatrix(Γ, N)
end
function covariancematrix(n::AbstractVector{<:Integer})
N = length(n)
D = diagm(-2 * n .+ 1)
Z = zeros(N, N)
CovarianceMatrix([Z D; -D Z], N)
end
#---------------------------------------------------------------------------------------------------
function fermioncorrelation(cm::CovarianceMatrix)
Γ, n = cm.Γ, cm.N
Γ11, Γ12, Γ21, Γ22 = Γ[1:n,1:n], Γ[1:n,n+1:2n], Γ[n+1:2n,1:n], Γ[n+1:2n,n+1:2n]
A = (Γ21 - Γ12 + 1im * Γ11 + 1im * Γ22) / 4 + I / 2
B = (Γ21 + Γ12 + 1im * Γ11 - 1im * Γ22) / 4
A, B
end
function fermioncorrelation(cm::CovarianceMatrix, i::Integer)
Γ, n = cm.Γ, cm.N
Γ11, Γ12, Γ21, Γ22 = Γ[1:n,1:n], Γ[1:n,n+1:2n], Γ[n+1:2n,1:n], Γ[n+1:2n,n+1:2n]
if i == 1
(Γ21 - Γ12 + 1im * Γ11 + 1im * Γ22) / 4 + I / 2
elseif i == 2
(Γ21 + Γ12 + 1im * Γ11 - 1im * Γ22) / 4
elseif i == 3
(-Γ21 - Γ12 + 1im * Γ11 - 1im * Γ22) / 4
else
error("i should equals to 1, 2, or 3.")
end
end
#---------------------------------------------------------------------------------------------------
# Evolution of Covariance Matrix
#---------------------------------------------------------------------------------------------------
function *(ql::QuardraticLindblad, Γ::AbstractMatrix{<:Real})
transpose(ql.X) * Γ + Γ * ql.X + sum(transpose(Zs) * Γ * Zs for Zs in ql.Z)
end
#---------------------------------------------------------------------------------------------------
function (ql::QuardraticLindblad)(cm::CovarianceMatrix, dt::Real=0.05; order::Integer=5)
Γ = cm.Γ
mat = Array(Γ)
dΓ = dt * (ql * Γ + ql.Y)
mat += dΓ
for i=2:order
dΓ = (dt/i) * (ql * dΓ)
mat += dΓ
end
CovarianceMatrix(mat, cm.N)
end
#---------------------------------------------------------------------------------------------------
"""
majoranaform(A::AbstractMatrix, B::AbstractMatrix)
Return the Majorana quadratic form
Ĥ = -i/4 ∑ Hᵢⱼ ωᵢωⱼ
from the fermion quadratic form
Ĥ = 1/2 ∑(Aᵢⱼ cᵢ⁺cⱼ + Bᵢⱼcᵢ⁺cⱼ⁺ + h.c.).
"""
function majoranaform(A::AbstractMatrix, B::AbstractMatrix)
AR, AI, BR, BI = real(A), imag(A), real(B), imag(B)
[-AI-BI AR-BR; -AR-BR -AI+BI]
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 2339 | #---------------------------------------------------------------------------------------------------
# Quantum Inverse Method
# Calculate Hamiltonian from eigen state(s).
#---------------------------------------------------------------------------------------------------
export covmat
"""
covmat(ol::AbstractVector, v::AbstractVecOrMat{<:Number})
Return the covariant matrix for a given list of operators:
Cᵢⱼ = 1/2⟨v|{hᵢ,hⱼ}|v⟩ - ⟨v|hᵢ|v⟩⟨v|hⱼ|v⟩,
or for a set of vector,
Cᵢⱼ = 1/2Tr[ρ{hᵢ,hⱼ}] - Tr[ρhᵢ]Tr[ρhⱼ],
where ρ = 1/N∑ₙ|vₙ⟩⟨vₙ|.
Inputs:
-------
- `ol`: List of operators, represented by matrices or `Operator`s.
- `V` : Target state represented by a vector, or target states represented by a matrix.
Outputs:
--------
- cm: (Symmetric real) matrix.
"""
function covmat(ol::AbstractVector, v::AbstractVecOrMat{<:Number})
n = length(ol)
vs = [oi * v for oi in ol]
am = [real(inner_product(v, vsi)) for vsi in vs]
cm = Matrix{Float64}(undef, n, n)
for i=1:n, j=i:n
cm[i, j] = real(inner_product(vs[i], vs[j])) - am[i] * am[j]
end
Symmetric(cm)
end
#---------------------------------------------------------------------------------------------------
export qimsolve
function qimsolve(ol::AbstractVector, v::AbstractVecOrMat{<:Number}; tol::Real=1e-7)
cm = covmat(ol, v)
e, v = eigen(cm)
i = findfirst(x -> x > tol, e) - 1
v[:, 1:i] |> simplify
end
#---------------------------------------------------------------------------------------------------
# Helper
#---------------------------------------------------------------------------------------------------
"""
Inner product ⟨v₁|v₂⟩. For two set of vector.
"""
function inner_product(v1::AbstractVecOrMat, v2::AbstractVecOrMat)
dot(v1, v2) / size(v1, 2)
end
#---------------------------------------------------------------------------------------------------
"""
Simplify the solutions.
"""
function simplify(h)
n = size(h, 2)
for i in 1:n
j = findfirst(x -> abs(x) > 1e-7, h[:,i])
for k in 1:n
isequal(k, i) && continue
h[:,k] .-= h[j,k] / h[j,i] * h[:,i]
end
end
for i in 1:n
j = findfirst(x -> abs(x) > 1e-7, h[:,i])
h[:,i] ./= h[j,i]
end
for i in eachindex(h)
abs(h[i]) < 1e-10 && (h[i] = 0.0)
end
h
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 7185 | include("../src/EDKit.jl")
using Main.EDKit, LinearAlgebra, Test, Profile
a = 1.0
b = randn()
c = randn()
d = randn()
e = randn()
f = randn()
mat = spin(
(a, "xx11"), (a, "yy11"),
(b, "x1x1"), (b, "y1y1"),
(c, "x11x"), (c, "y11y"),
(d, "zz11"),
(e, "z1z1"),
(f, "z11z")
)
function add_value!(E, B)
iszero(size(B, 1)) && return
vals = trans_inv_operator(mat, 4, B) |> Hermitian |> eigvals
append!(E, vals)
end
@testset "1-sym-vals" begin
for L in 4:10
B = basis(;L)
E = trans_inv_operator(mat, 4, B) |> Hermitian |> eigvals
# N total
Es = []
for N in 0:L
B = basis(;L, N)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# P
Es = []
for p in [1, -1]
B = basis(;L, p)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# Z
Es = []
for z in [1, -1]
B = basis(;L, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# k
Es = []
for k in 0:L-1
B = basis(;L, k)
add_value!(Es, B)
end
@test sort(Es) ≈ E
end
end
@testset "2-sym-vals" begin
for L in 4:10
E = trans_inv_operator(mat, 4, L) |> Hermitian |> eigvals
# N + P
Es = []
for N in 0:L, p in [1, -1]
B = basis(;L, N, p)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# N + k
Es = []
for N in 0:L, k in 0:L-1
B = basis(;L, N, k)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# N + Z
# P + Z
Es = []
for p in [1, -1], z in [1, -1]
B = basis(;L, p, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# k + Z
Es = []
for k in 0:L-1, z in [1, -1]
B = basis(;L, k, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# k + P
end
end
@testset "Half-k" begin
for L in 4:2:10, k in [0, L÷2]
B = basis(;L, k); iszero(size(B, 1)) && continue
E = trans_inv_operator(mat, 4, B) |> Hermitian |> eigvals
# k + P
Es = []
for p in [1, -1]
B = basis(;L, k, p)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# k + P + Z
Es = []
for p in [1, -1], z in [1, -1]
B = basis(;L, k, p, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# k + P + N
Es = []
for N in 0:L, p in [1, -1]
B = basis(;L, N, k, p)
add_value!(Es, B)
end
@test sort(Es) ≈ E
end
end
@testset "Half-filling" begin
for L in 4:2:10
N = L÷2
B = basis(;L, N); iszero(size(B, 1)) && continue
E = trans_inv_operator(mat, 4, B) |> Hermitian |> eigvals
# N + Z
Es = []
for z in [1, -1]
B = basis(;L, N, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# N + Z + P
Es = []
for z in [1, -1], p in [1, -1]
B = basis(;L, N, p, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
# N + Z + k
Es = []
for k in 0:L-1, z in [1, -1]
B = basis(;L, N, k, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
end
end
@testset "Symmetric" begin
for L in 4:2:12, k in [0, L÷2]
N = L÷2
B = basis(;L, N, k); iszero(size(B, 1)) && continue
E = trans_inv_operator(mat, 4, B) |> Hermitian |> eigvals
# N + k + P + Z
Es = []
for p in [1, -1], z in [1, -1]
B = basis(;L, N, k, p, z)
add_value!(Es, B)
end
@test sort(Es) ≈ E
end
end
function add_value!(M::AbstractMatrix, E, S, B)
iszero(size(B, 1)) && return
e, v = trans_inv_operator(M, round(Int, log(2, size(M, 1))), B) |> Hermitian |> eigen
append!(E, e)
inds = 1:length(B)÷2
s = [ent_S(v[:, i], inds, B) for i in axes(v, 2)]
append!(S, s)
end
function add_value!(Ms::Vector, E, S, B)
iszero(size(B, 1)) && return
n = round(Int, log(2, size(Ms[1], 1)))
L = length(B)
inds = [mod.(i-1:i+n-2, L) .+ 1 for i in 1:L]
e, v = operator(Ms, inds, B) |> Hermitian |> eigen
append!(E, e)
s = [ent_S(v[:, i], 1:L÷2, B) for i in axes(v, 2)]
append!(S, s)
end
@testset "Relax k" begin
for L in 4:8
M = randn(ComplexF64, 8, 8) |> Hermitian |> Array
B = basis(;L); iszero(size(B, 1)) && continue
E, V = trans_inv_operator(M, 3, B) |> Hermitian |> eigen
S = [ent_S(V[:, i], 1:L÷2, B) for i in axes(V, 2)] |> sort
Es, Ss = [], []
for k in 0:L-1
B = basis(;L, k)
add_value!(M, Es, Ss, B)
end
@test sort(Es) ≈ E
@test norm(sort(Ss) - S) < 1e-7
end
end
@testset "Relax N" begin
a = 1.0
b = randn()
c = randn()
d = randn()
e = randn()
f = 5
mat = spin(
(a, "xx11"), (a, "yy11"),
(b, "x1x1"), (b, "y1y1"),
(c, "x11x"), (c, "y11y"),
(d, "zz11"),
(e, "z1z1"),
(f, "z111")
)
for L in 4:8
mats = [randn()*mat for i in 1:L]
inds = [mod.(i-1:i+2, L) .+ 1 for i in 1:L]
B = basis(;L); iszero(size(B, 1)) && continue
E, V = operator(mats, inds, B) |> Hermitian |> eigen
S = [ent_S(V[:, i], 1:L÷2, B) for i in axes(V, 2)] |> sort
Es, Ss = [], []
for N in 0:L
B = basis(;L, N)
add_value!(mats, Es, Ss, B)
end
@test sort(Es) ≈ E
@test norm(sort(Ss) - S) < 1e-7
end
end
@testset "k -> N" begin
a = 1.0
b = randn()
c = randn()
d = randn()
e = randn()
f = 5
mat = spin(
(a, "xx11"), (a, "yy11"),
(b, "x1x1"), (b, "y1y1"),
(c, "x11x"), (c, "y11y"),
(d, "zz11"),
(e, "z1z1"),
(f, "z111")
)
for L in 4:8, k in 0:L-1
B = basis(;L, k); iszero(size(B, 1)) && continue
E, V = trans_inv_operator(mat, 4, B) |> Hermitian |> eigen
S = [ent_S(V[:, i], 1:L÷2, B) for i in axes(V, 2)] |> sort
Es, Ss = [], []
for N in 0:L
B = basis(;L, N, k)
add_value!(mat, Es, Ss, B)
end
@test sort(Es) ≈ E
@test norm(sort(Ss) - S) < 1e-7
end
end
@testset "N k -> P Z" begin
for L in 4:2:12, k in [0, L÷2]
N = L÷2
# N + k + P + Z
B = basis(;L, N, k); iszero(size(B, 1)) && continue
E, V = trans_inv_operator(mat, 4, B) |> Hermitian |> eigen
S = [ent_S(V[:, i], 1:L÷2, B) for i in axes(V, 2)] |> sort
Es, Ss = [], []
for p in [1, -1], z in [1, -1]
B = basis(;L, N, k, p, z)
add_value!(mat, Es, Ss, B)
end
@test sort(Es) ≈ E
@test sort(Ss) ≈ S
end
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 1616 | using LinearAlgebra
include("../src/EDKit.jl")
using .EDKit
using Test
@testset "Basic" begin
L = 10
b1 = TranslationalBasis(N=2, k=0, L=L)
b2 = TranslationalBasis(N=0, k=1, L=L)
b = DoubleBasis(b1, b2)
mat = rand(2,2) |> Hermitian
H = trans_inv_operator(mat, 1, b) |> Array
@test size(H) == (5, 0)
end
@testset "Spin-1 Random" begin
L = 6
Sp = begin
p3 = [1]
p2 = [2, 4, 10]
p1 = [3, 5, 7, 11, 13, 19]
z0 = [6, 8, 12, 14, 16, 20, 22]
m1 = [9, 15, 17, 21, 23, 25]
m2 = [18, 24, 26]
m3 = [27]
mat = zeros(ComplexF64, 27, 27)
mat[m2, m3] .= rand(ComplexF64, 3, 1)
mat[m1, m2] .= rand(ComplexF64, 6, 3)
mat[z0, m1] .= rand(ComplexF64, 7, 6)
mat[p1, z0] .= rand(ComplexF64, 6, 7)
mat[p2, p1] .= rand(ComplexF64, 3, 6)
mat[p3, p2] .= rand(ComplexF64, 1, 3)
mat
end
XY = spin((1, "+-"), (1, "-+"), (1, "z1"), (1, "1z"), D=3)
A = 0.0
for n = 1:2L
b1 = ProjectedBasis(f=x -> sum(x)==(n-1), L=L, base=3)
b2 = ProjectedBasis(f=x -> sum(x)==n, L=L, base=3)
basis = DoubleBasis(b1, b2)
e1, v1 = trans_inv_operator(XY, 2, b1) |> Array |> Hermitian |> eigen
e2, v2 = trans_inv_operator(XY, 2, b2) |> Array |> Hermitian |> eigen
op = trans_inv_operator(Sp, 3, basis) |> Array
A += abs2.(v1' * op * v2) |> sum
end
e, v = trans_inv_operator(XY, 2, L) |> Array |> Hermitian |> eigen
op = trans_inv_operator(Sp, 3, L) |> Array
B = abs2.(v' * op * v) |> sum
@test A ≈ B atol = 1e-7
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 24658 | include("../src/EDKit.jl")
using .EDKit
using LinearAlgebra
using Test
#-------------------------------------------------------------------------------------------------------------------------
# Tesnsor Basis
#-------------------------------------------------------------------------------------------------------------------------
println("--------------------------------------------------")
println(" Tensor Basis ")
println("--------------------------------------------------")
const X = [0 1; 1 0]
const Y = [0 -1; 1 0] * 1im
const Z = [1 0; 0 -1]
directkron(mat, i, j, L, base=2) = kron(I(base^(i-1)), mat, I(base^(L-j)))
boundarykron(m1, m2, i, j, base=2) = kron(m1, I(base^(j-i+1)), m2)
#-------------------------------------------------------------------------------------------------------------------------
@testset "Base-2 Random Kron" begin
L = 10
for i=1:10
mats = [rand(2^i, 2^i) for j=1:L-i+1]
inds = [j:j+i-1 for j=1:L-i+1]
M_test = operator(mats, inds, L) |> Array
M_targ = sum(directkron(mats[j], j, j+i-1, L) for j = 1:L-i+1)
@test M_test ≈ M_targ
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Base-3 Random Kron" begin
L = 6
for i=1:6
mats = [rand(3^i, 3^i) for j=1:L-i+1]
inds = [j:j+i-1 for j=1:L-i+1]
M_test = operator(mats, inds, L) |> Array
M_targ = sum(directkron(mats[j], j, j+i-1, L, 3) for j = 1:L-i+1)
@test M_test ≈ M_targ
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Base-3 Boundary Kron" begin
L = 6
for i = 1:3, j = 1:3
m1, m2 = rand(3^i, 3^i), rand(3^j, 3^j)
mats = kron(m1, m2)
inds = vcat(Vector(1:i), Vector(L-j+1:L))
M_test = operator(mats, inds, L) |> Array
M_targ = boundarykron(m1, m2, i+1, L-j, 3)
@test M_test ≈ M_targ
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Operator Multiplication" begin
L = 10
mat = kron(I(2), X, Y, Z)
v = rand(2^L)
opt = trans_inv_operator(mat, 4, L)
v2 = opt * v
optm = Array(opt)
v3 = optm * v
@test v2 ≈ v3
end
#-------------------------------------------------------------------------------------------------------------------------
# Projected Basis
#-------------------------------------------------------------------------------------------------------------------------
println("--------------------------------------------------")
println(" Projected Basis ")
println("--------------------------------------------------")
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 XY" begin
L = 8
mat = spin((1, "xx"), (1, "yy"))
E = zeros(2^L)
P = 0
for n = 0:L
basis = ProjectedBasis(f=x->sum(x)==n, L=L)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 Random" begin
L = 8
mat = begin
M = zeros(ComplexF64, 8, 8)
M[1,1] = rand()
M[8,8] = rand()
M[[2,3,5], [2,3,5]] = rand(ComplexF64, 3, 3) |> Hermitian
M[[4,6,7], [4,6,7]] = rand(ComplexF64, 3, 3) |> Hermitian
M
end
E = zeros(2^L)
P = 0
for n = 0:L
basis = ProjectedBasis(f=x->sum(x)==n, L=L)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 3, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 3, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "PXP_OBC" begin
function fib(n::Integer)
iszero(n) && return 1
isone(n) && return 2
a, b = 1, 2
for m = 2:n
a, b = b, a+b
end
b
end
mat = begin
P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])
P * kron(I(2), X, I(2)) * P
end
pxpf(v::Vector{<:Integer}) = all(v[i]==0 || v[i+1]==0 for i=1:length(v)-1)
for L = 3:20
basis = ProjectedBasis(f=pxpf, L=L)
@test size(basis, 1) == fib(L)
end
for L = 3:10
basis = ProjectedBasis(f=pxpf, L=L)
mats = fill(mat, L-2)
inds = [[i,i+1, i+2] for i=1:L-2]
E = operator(mats, inds, basis) |> Array |> Hermitian |> eigvals
H = operator(mats, inds, L) |> Array
vals = H[basis.I, basis.I] |> Hermitian |> eigvals
@test norm(vals - E) ≈ 0.0
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "PXP_PBC Projected Basis" begin
mat = begin
P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])
P * kron(I(2), X, I(2)) * P
end
pxpf(v::Vector{<:Integer}) = all(v[i]==0 || v[mod(i, length(v))+1]==0 for i=1:length(v))
for L = 3:14
basis = ProjectedBasis(f=pxpf, L=L)
E = trans_inv_operator(mat, 3, basis) |> Array |> Hermitian |> eigvals
H = trans_inv_operator(mat, 3, L) |> Array
vals = H[basis.I, basis.I] |> Hermitian |> eigvals
@test norm(vals - E) ≈ 0.0
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1 Random" begin
L = 6
R3 = begin
m2 = [2, 4, 10]
m1 = [3, 5, 7, 11, 13, 19]
m0 = [6, 8, 12, 14, 16, 20, 22]
p1 = [9, 15, 17, 21, 23, 25]
p2 = [18, 24, 26]
mat = zeros(ComplexF64, 27, 27)
mat[1, 1] = rand()
mat[27, 27] = rand()
mat[m2, m2] .= rand(ComplexF64, 3, 3) |> Hermitian
mat[m1, m1] .= rand(ComplexF64, 6, 6) |> Hermitian
mat[m0, m0] .= rand(ComplexF64, 7, 7) |> Hermitian
mat[p1, p1] .= rand(ComplexF64, 6, 6) |> Hermitian
mat[p2, p2] .= rand(ComplexF64, 3, 3) |> Hermitian
mat
end
E = zeros(3^L)
P = 0
for n = 0:2L
basis = ProjectedBasis(f=x->sum(x)==n, L=L, base=3)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 3, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 3^L
vals = trans_inv_operator(mat, 3, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "BigInt" begin
L = 10
mat = spin((1, "xx"), (1, "yy"))
E = zeros(2^L)
P = 0
for n = 0:L
basis = ProjectedBasis(BigInt, f=x->sum(x)==n, L=L)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "small_N off" begin
L = 10
mat = spin((1, "xx"), (1, "yy"))
E = zeros(2^L)
P = 0
for n = 0:L
basis = ProjectedBasis(f=x->sum(x)==n, L=L, small_N=false)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
println("--------------------------------------------------")
println(" Parity Basis ")
println("--------------------------------------------------")
#-------------------------------------------------------------------------------------------------------------------------
@testset "PXP" begin
mat = begin
P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])
P * kron(I(2), X, I(2)) * P
end
pxpf(v::Vector{<:Integer}) = all(v[i]==0 || v[mod(i, length(v))+1]==0 for i=1:length(v))
for L = 3:12
ba = ProjectedBasis(f=pxpf, L=L)
be = ParityBasis(f=pxpf, L=L, p=1)
bo = ParityBasis(f=pxpf, L=L, p=-1)
@test size(be, 1) + size(bo, 1) == size(ba, 1)
Ea = trans_inv_operator(mat, 3, ba) |> Hermitian |> eigvals
Ee = trans_inv_operator(mat, 3, be) |> Hermitian |> eigvals
Eo = trans_inv_operator(mat, 3, bo) |> Hermitian |> eigvals
Eeo = sort(vcat(Ee, Eo))
@test norm(Ea - Eeo) ≈ 0.0 atol = 1e-12
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 XY" begin
mat = spin((1, "xx"), (1, "yy"))
for L = 2:8, n = 0:L
ba = ProjectedBasis(N=n, L=L)
be = ParityBasis(N=n, L=L, p=1)
bo = ParityBasis(N=n, L=L, p=-1)
@test size(be, 1) + size(bo, 1) == size(ba, 1)
Ea = trans_inv_operator(mat, 2, ba) |> Hermitian |> eigvals
Ee = trans_inv_operator(mat, 2, be) |> Hermitian |> eigvals
Eo = trans_inv_operator(mat, 2, bo) |> Hermitian |> eigvals
Eeo = sort(vcat(Ee, Eo))
@test norm(Ea - Eeo) ≈ 0.0 atol = 1e-12
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "BigInt" begin
L = 6
mat = spin((1, "xx"), (1, "yy"))
for n = 0:L
ba = ProjectedBasis(N=n, L=L)
be = ParityBasis(BigInt, N=n, L=L, p=1)
bo = ParityBasis(BigInt, N=n, L=L, p=-1)
@test size(be, 1) + size(bo, 1) == size(ba, 1)
Ea = trans_inv_operator(mat, 2, ba) |> Hermitian |> eigvals
Ee = trans_inv_operator(mat, 2, be) |> Hermitian |> eigvals
Eo = trans_inv_operator(mat, 2, bo) |> Hermitian |> eigvals
Eeo = sort(vcat(Ee, Eo))
@test norm(Ea - Eeo) ≈ 0.0 atol = 1e-12
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1 XY Spin-flip" begin
for L = 2:4
N = L
mat = spin((1, "xx"), (1, "yy"), D=3)
ba = ProjectedBasis(N=N, L=L, base=3)
be = FlipBasis(N=N, L=L, p=1, base=3)
bo = FlipBasis(N=N, L=L, p=-1, base=3)
@test size(be, 1) + size(bo, 1) == size(ba, 1)
Ea = trans_inv_operator(mat, 2, ba) |> Hermitian |> eigvals
Ee = trans_inv_operator(mat, 2, be) |> Hermitian |> eigvals
Eo = trans_inv_operator(mat, 2, bo) |> Hermitian |> eigvals
Eeo = sort(vcat(Ee, Eo))
@test norm(Ea - Eeo) ≈ 0.0 atol = 1e-12
end
end
#-------------------------------------------------------------------------------------------------------------------------
println("--------------------------------------------------")
println(" ParityFlip Basis ")
println("--------------------------------------------------")
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 XY" begin
mat = spin((1, "xx"), (1, "yy"), (0.3, "zz"))
for L = 2:6
b1 = ParityFlipBasis(L=L, p=+1, z=+1)
b2 = ParityFlipBasis(L=L, p=+1, z=-1)
b3 = ParityFlipBasis(L=L, p=-1, z=+1)
b4 = ParityFlipBasis(L=L, p=-1, z=-1)
@test size(b1, 1) + size(b2, 1) + size(b3, 1) + size(b4, 1) == 2^L
Ea = trans_inv_operator(mat, 2, L) |> Hermitian |> eigvals
E1 = trans_inv_operator(mat, 2, b1) |> Hermitian |> eigvals
E2 = trans_inv_operator(mat, 2, b2) |> Hermitian |> eigvals
E3 = trans_inv_operator(mat, 2, b3) |> Hermitian |> eigvals
E4 = trans_inv_operator(mat, 2, b4) |> Hermitian |> eigvals
E = sort(vcat(E1, E2, E3, E4))
@test norm(Ea - E) ≈ 0.0 atol = 1e-12
end
end
#-------------------------------------------------------------------------------------------------------------------------
# Translation Basis
#-------------------------------------------------------------------------------------------------------------------------
println("--------------------------------------------------")
println(" Translational Basis ")
println("--------------------------------------------------")
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 XY" begin
L = 10
θ = 0.34
expθ = exp(-1im*θ)
mat = spin((expθ, "+-"), (1/expθ, "-+"), (1, "z1"), (1, "1z"))
E = zeros(2^L)
P = 0
for n = 0:L, k = 0:L-1
basis = TranslationalBasis(N=n, k=k, L=L)
#println(size(basis,1))
if (l = size(basis,1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "XY 2-site-cell" begin
L = 10
θ = rand()
expθ = exp(-1im*θ)
mat = spin((expθ, "+-"), (1/expθ, "-+"), (1, "z1"), (1, "1z"))
E = zeros(2^L)
P = 0
for n = 0:L, k = 0:L÷2-1
basis = TranslationalBasis(N=n, k=k, L=L, a=2)
#println(size(basis,1))
if (l = size(basis,1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 Random" begin
L = 10
mat = begin
M = zeros(ComplexF64, 8, 8)
M[1,1] = rand()
M[8,8] = rand()
M[[2,3,5], [2,3,5]] = rand(ComplexF64, 3, 3) |> Hermitian
M[[4,6,7], [4,6,7]] = rand(ComplexF64, 3, 3) |> Hermitian
M
end
E = zeros(2^L)
P = 0
for n = 0:L, k = 0:L-1
basis = TranslationalBasis(f=x->sum(x)==n, k=k, L=L)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 3, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 2^L
vals = trans_inv_operator(mat, 3, L) |> Array |> Hermitian |> eigvals
@test norm(vals - sort(E)) ≈ 0.0 atol = 1e-10
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1 XY" begin
L = 6
h = 1
mat = spin((1, "xx"), (1, "yy"), (h/2, "1z"), (h/2, "z1"), D=3)
E = zeros(3^L)
P = 0
for n = 0:2L, k = 0:L-1
basis = TranslationalBasis(f=x->sum(x)==n, k=k, L=L, base=3)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
@test P == 3^L
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "AKLT" begin
L = 6
mat = begin
ss = spin((1, "xx"), (1, "yy"), (1, "zz"), D=3)
1/2 * ss + 1/6 * ss^2 + 1/3 * I
end
E = zeros(3^L)
P = 0
for n = 0:2L, k = 0:L-1
basis = TranslationalBasis(f=x->sum(x)==n, k=k, L=L, base=3)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 2, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
vals = trans_inv_operator(mat, 2, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1 Random" begin
L = 6
mat = begin
m2 = [2, 4, 10]
m1 = [3, 5, 7, 11, 13, 19]
m0 = [6, 8, 12, 14, 16, 20, 22]
p1 = [9, 15, 17, 21, 23, 25]
p2 = [18, 24, 26]
M = zeros(ComplexF64, 27, 27)
M[1, 1] = rand()
M[27, 27] = rand()
M[m2, m2] .= rand(ComplexF64, 3, 3) |> Hermitian
M[m1, m1] .= rand(ComplexF64, 6, 6) |> Hermitian
M[m0, m0] .= rand(ComplexF64, 7, 7) |> Hermitian
M[p1, p1] .= rand(ComplexF64, 6, 6) |> Hermitian
M[p2, p2] .= rand(ComplexF64, 3, 3) |> Hermitian
M
end
E = zeros(3^L)
P = 0
for n = 0:2L, k = 0:L-1
basis = TranslationalBasis(f=x->sum(x)==n, k=k, L=L, base=3)
if (l = size(basis, 1)) > 0
vals = trans_inv_operator(mat, 3, basis) |> Array |> Hermitian |> eigvals
E[P+1:P+l] = vals
P += l
end
end
vals = trans_inv_operator(mat, 3, L) |> Array |> Hermitian |> eigvals
@test vals ≈ sort!(E)
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "SO(3) qsymm" begin
L = 6
h = rand()
rh = begin
vecs = zeros(ComplexF64, 9, 4)
vecs[8,1] = 1
vecs[6,1] = -1
vecs[7,2] = 1
vecs[3,2] = -1
vecs[4,3] = 1
vecs[2,3] = -1
vecs[3,4] = 1
vecs[5,4] = -1
vecs[7,4] = 1
rm = rand(ComplexF64, 4,4) .- 0.5 |> Hermitian |> Array
vecs * rm * vecs'
end
H = trans_inv_operator(rh, 2, L)
H += trans_inv_operator(spin((h, "z"), D=3), 1, L)
E = Array(H) |> Hermitian |> eigvals
es = Float64[]
for i = 0:L-1
tb = TranslationalBasis(k=i, L=L, base=3)
H = trans_inv_operator(rh, 2, tb)
H += trans_inv_operator(spin((h, "z"), D=3), 1, tb)
e = Array(H) |> Hermitian |> eigvals
append!(es, e)
end
@test norm(sort(E) - sort(es)) ≈ 0.0 atol = 1e-7
end
#-------------------------------------------------------------------------------------------------------------------------
# Translation + Parity
#-------------------------------------------------------------------------------------------------------------------------
println("--------------------------------------------------")
println(" Translation Parity Basis ")
println("--------------------------------------------------")
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1/2 XY" begin
mat = spin((1, "+-"), (1, "-+"), (1, "z1"), (1, "1z"))
for L = 2:2:10
for n = 0:L, k in [0, L ÷ 2]
be = TranslationParityBasis(f=x->sum(x)==n, k=k, p=+1, L=L)
bo = TranslationParityBasis(f=x->sum(x)==n, k=k, p=-1, L=L)
ba = TranslationalBasis(f=x->sum(x)==n, k=k, L=L)
ve = trans_inv_operator(mat, 2, be) |> Array |> Hermitian |> eigvals
vo = trans_inv_operator(mat, 2, bo) |> Array |> Hermitian |> eigvals
va = trans_inv_operator(mat, 2, ba) |> Array |> Hermitian |> eigvals
E = sort(vcat(ve, vo))
@test norm(E-va) ≈ 0.0 atol = 1e-12
end
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Spin-1 XY" begin
mat = spin((1, "+-"), (1, "-+"), (1, "z1"), (1, "1z"), D=3)
for L = 2:2:6
for n = 0:2L, k in [0, L ÷ 2]
be = TranslationParityBasis(f=x->sum(x)==n, k=k, p=+1, L=L, base=3)
bo = TranslationParityBasis(f=x->sum(x)==n, k=k, p=-1, L=L, base=3)
ba = TranslationalBasis(f=x->sum(x)==n, k=k, L=L, base=3)
ve = trans_inv_operator(mat, 2, be) |> Array |> Hermitian |> eigvals
vo = trans_inv_operator(mat, 2, bo) |> Array |> Hermitian |> eigvals
va = trans_inv_operator(mat, 2, ba) |> Array |> Hermitian |> eigvals
E = sort(vcat(ve, vo))
@test norm(E-va) ≈ 0.0 atol = 1e-12
end
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "PXP" begin
mat = begin
P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])
P * kron(I(2), X, I(2)) * P
end
pxpf(v::Vector{<:Integer}) = all(v[i]==0 || v[mod(i, length(v))+1]==0 for i=1:length(v))
for L = 4:2:16
for k in [0, L ÷ 2]
be = TranslationParityBasis(f=pxpf, k=k, p=1, L=L)
bo = TranslationParityBasis(f=pxpf, k=k, p=-1, L=L)
ba = TranslationalBasis(f=pxpf, k=k, L=L)
ve = trans_inv_operator(mat, 2, be) |> Array |> Hermitian |> eigvals
vo = trans_inv_operator(mat, 2, bo) |> Array |> Hermitian |> eigvals
va = trans_inv_operator(mat, 2, ba) |> Array |> Hermitian |> eigvals
E = sort(vcat(ve, vo))
@test norm(E-va) ≈ 0.0 atol = 1e-12
end
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Ising Spin-flip" begin
zz = spin((1, "zz"))
x = spin((0.3,"x"))
for L = 4:2:10
E = zeros(2^L)
for k in 0:L-1
ba = TranslationalBasis(k=k, L=L)
be = TranslationFlipBasis(k=k, p=1, L=L)
bo = TranslationFlipBasis(k=k, p=-1, L=L)
va = trans_inv_operator(zz, 2, ba) + trans_inv_operator(x, 1, ba) |> Array |> Hermitian |> eigvals
ve = trans_inv_operator(zz, 2, be) + trans_inv_operator(x, 1, be) |> Array |> Hermitian |> eigvals
vo = trans_inv_operator(zz, 2, bo) + trans_inv_operator(x, 1, bo) |> Array |> Hermitian |> eigvals
veo = sort(vcat(ve, vo))
@test norm(va-veo) ≈ 0.0 atol = 1e-12
end
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "XY 2-site-cell" begin
mat = spin((1, "+-"), (1, "-+"), (1, "z1"), (1, "1z"))
L = 8
for n = 0:L, k in [0, L ÷ 4]
be = TranslationParityBasis(N=n, k=k, p=+1, L=L, a=2)
bo = TranslationParityBasis(N=n, k=k, p=-1, L=L, a=2)
ba = TranslationalBasis(f=x->sum(x)==L-n, k=k, L=L, a=2)
ve = trans_inv_operator(mat, 2, be) |> Array |> Hermitian |> eigvals
vo = trans_inv_operator(mat, 2, bo) |> Array |> Hermitian |> eigvals
va = trans_inv_operator(mat, 2, ba) |> Array |> Hermitian |> eigvals
E = sort(vcat(ve, vo))
@test norm(E-va) ≈ 0.0 atol = 1e-12
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Ising 3-site-cell" begin
zz = spin((1, "zz"))
x = spin((0.3,"x"))
L = 9
E = zeros(2^L)
for k in 0:L÷3-1
ba = TranslationalBasis(k=k, L=L, a=3)
be = TranslationFlipBasis(k=k, p=1, L=L, a=3)
bo = TranslationFlipBasis(k=k, p=-1, L=L, a=3)
va = trans_inv_operator(zz, 2, ba) + trans_inv_operator(x, 1, ba) |> Array |> Hermitian |> eigvals
ve = trans_inv_operator(zz, 2, be) + trans_inv_operator(x, 1, be) |> Array |> Hermitian |> eigvals
vo = trans_inv_operator(zz, 2, bo) + trans_inv_operator(x, 1, bo) |> Array |> Hermitian |> eigvals
veo = sort(vcat(ve, vo))
@test norm(va-veo) ≈ 0.0 atol = 1e-12
end
end | EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 7418 | include("../src/EDKit.jl")
using .EDKit
using LinearAlgebra, Test
#-------------------------------------------------------------------------------------------------------------------------
@testset "Random Hamiltonian" begin
L = 6
rm = randn(ComplexF64, 9, 9) |> Hermitian |> Array
# Tensor Basis:
B0 = TensorBasis(L=L, base=3)
H0 = trans_inv_operator(rm, 2, B0)
E, V = Array(H0) |> Hermitian |> eigen
S = [ent_S(V[:, i], 1:L÷2, B0) for i in axes(V, 2)]
# Momentum Resolved Bases:
E2 = Float64[]
S2 = Float64[]
for i = 0:L-1
B = TranslationalBasis(k=i, L=L, base=3)
H = trans_inv_operator(rm, 2, B)
e, v = Array(H) |> Hermitian |> eigen
append!(E2, e)
for j in axes(v, 2)
push!(S2, ent_S(v[:, j], 1:L÷2, B))
end
end
perm = sortperm(E2)
@test E ≈ E2[perm]
@test S ≈ S2[perm]
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Random: 2-site-cell" begin
L = 6
rm = randn(ComplexF64, 9, 9) |> Hermitian |> Array
# Tensor Basis:
B0 = TensorBasis(L=L, base=3)
H0 = trans_inv_operator(rm, 2, B0)
E, V = Array(H0) |> Hermitian |> eigen
S = [ent_S(V[:, i], 1:L÷2, B0) for i in axes(V, 2)]
# Momentum Resolved Bases:
E2 = Float64[]
S2 = Float64[]
for i = 0:L÷2-1
B = TranslationalBasis(k=i, L=L, base=3, a=2)
H = trans_inv_operator(rm, 2, B)
e, v = Array(H) |> Hermitian |> eigen
append!(E2, e)
for j in axes(v, 2)
push!(S2, ent_S(v[:, j], 1:L÷2, B))
end
end
perm = sortperm(E2)
@test E ≈ E2[perm]
@test S ≈ S2[perm]
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Qsymm: T+P" begin
L = 6
h = rand()
perm = [1, 4, 7, 2, 5, 8, 3, 6, 9]
rh = begin
vecs = zeros(ComplexF64, 9, 4)
vecs[8,1] = 1
vecs[6,1] = -1
vecs[7,2] = 1
vecs[3,2] = -1
vecs[4,3] = 1
vecs[2,3] = -1
vecs[3,4] = 1
vecs[5,4] = -1
vecs[7,4] = 1
rm = rand(ComplexF64, 4,4) .- 0.5 |> Hermitian |> Array
mat = vecs * rm * vecs'
mat + mat[perm, perm]
end
function solve(basis)
H = trans_inv_operator(rh, 2, basis)
H += trans_inv_operator(spin((h, "z"), D=3), 1, basis)
e, v = Array(H) |> Hermitian |> eigen
v
end
EE(v, inds, basis) = [ent_S(v[:, i], inds, basis) for i in axes(v, 2)]
# K = 0
ba = TranslationalBasis(k=0, L=L, base=3)
be = TranslationParityBasis(k=0, p=+1, L=L, base=3)
bo = TranslationParityBasis(k=0, p=-1, L=L, base=3)
va, ve, vo = solve(ba), solve(be), solve(bo)
for inds in Any[1:L÷2, [1,2], [3,5], [2,4,6]]
eea = EE(va, inds, ba)
eee = EE(ve, inds, be)
eeo = EE(vo, inds, bo)
@test norm(sort(eea) - sort(vcat(eee, eeo))) ≈ 0.0 atol = 1e-7
end
# K = π
ba = TranslationalBasis(k=L÷2, L=L, base=3)
be = TranslationParityBasis(k=L÷2, p=+1, L=L, base=3)
bo = TranslationParityBasis(k=L÷2, p=-1, L=L, base=3)
va, ve, vo = solve(ba), solve(be), solve(bo)
for inds in Any[1:L÷2, [1,2], [3,5], [2,4,6]]
eea = EE(va, inds, ba)
eee = EE(ve, inds, be)
eeo = EE(vo, inds, bo)
@test norm(sort(eea) - sort(vcat(eee, eeo))) ≈ 0.0 atol = 1e-7
end
end
#-------------------------------------------------------------------------------------------------------------------------
@testset "Qsymm: T+P 2-cell" begin
L = 4
h = rand()
perm = [1, 4, 7, 2, 5, 8, 3, 6, 9]
rh = begin
vecs = zeros(ComplexF64, 9, 4)
vecs[8,1] = 1
vecs[6,1] = -1
vecs[7,2] = 1
vecs[3,2] = -1
vecs[4,3] = 1
vecs[2,3] = -1
vecs[3,4] = 1
vecs[5,4] = -1
vecs[7,4] = 1
rm = rand(ComplexF64, 4,4) .- 0.5 |> Hermitian |> Array
mat = vecs * rm * vecs'
mat + mat[perm, perm]
end
function solve(basis)
H = trans_inv_operator(rh, 2, basis)
H += trans_inv_operator(spin((h, "z"), D=3), 1, basis)
e, v = Array(H) |> Hermitian |> eigen
v
end
EE(v, inds, basis) = [ent_S(v[:, i], inds, basis) for i in axes(v, 2)]
# K = 0
ba = TranslationalBasis(k=0, L=L, base=3, a=2)
be = TranslationParityBasis(k=0, p=+1, L=L, base=3, a=2)
bo = TranslationParityBasis(k=0, p=-1, L=L, base=3, a=2)
va, ve, vo = solve(ba), solve(be), solve(bo)
for inds in Any[[1,2], [1,3], [1,4,2]]
eea = EE(va, inds, ba)
eee = EE(ve, inds, be)
eeo = EE(vo, inds, bo)
@test norm(sort(eea) - sort(vcat(eee, eeo))) ≈ 0.0 atol = 1e-7
end
# K = π
ba = TranslationalBasis(k=L÷2, L=L, base=3, a=2)
be = TranslationParityBasis(k=L÷2, p=+1, L=L, base=3, a=2)
bo = TranslationParityBasis(k=L÷2, p=-1, L=L, base=3, a=2)
va, ve, vo = solve(ba), solve(be), solve(bo)
for inds in Any[[1,4], [3,2], [2,4,3]]
eea = EE(va, inds, ba)
eee = EE(ve, inds, be)
eeo = EE(vo, inds, bo)
@test norm(sort(eea) - sort(vcat(eee, eeo))) ≈ 0.0 atol = 1e-7
end
end
#-------------------------------------------------------------------------------------------------------------------------
# Random model with spin-flip symmetry
#-------------------------------------------------------------------------------------------------------------------------
@testset "Random spin-flip" begin
L = 6
perm = [9,8,7,6,5,4,3,2,1]
rh = begin
mat = rand(ComplexF64, 9, 9) |> Hermitian |> Array
mat + mat[perm, perm]
end
function solve(basis)
H = trans_inv_operator(rh, 2, basis)
e, v = Array(H) |> Hermitian |> eigen
v
end
EE(v, inds, basis) = [ent_S(v[:, j], inds, basis) for j in axes(v, 2)]
for i = 0:L-1
ba = TranslationalBasis(k=i, L=L, base=3)
be = TranslationFlipBasis(k=i, p=+1, L=L, base=3)
bo = TranslationFlipBasis(k=i, p=-1, L=L, base=3)
va, ve, vo = solve(ba), solve(be), solve(bo)
for inds in Any[1:L÷2, [1,2], [3,5], [2,4,6]]
eea = EE(va, inds, ba)
eee = EE(ve, inds, be)
eeo = EE(vo, inds, bo)
@test norm(sort(eea) - sort(vcat(eee, eeo))) ≈ 0.0 atol = 1e-7
end
end
end
@testset "Random spin-flip 2-cell" begin
L = 4
perm = [9,8,7,6,5,4,3,2,1]
rh = begin
mat = rand(ComplexF64, 9, 9) |> Hermitian |> Array
mat + mat[perm, perm]
end
function solve(basis)
H = trans_inv_operator(rh, 2, basis)
e, v = Array(H) |> Hermitian |> eigen
v
end
EE(v, inds, basis) = [ent_S(v[:, j], inds, basis) for j in axes(v, 2)]
for i = 0:L÷2-1
ba = TranslationalBasis(k=i, L=L, base=3, a=2)
be = TranslationFlipBasis(k=i, p=+1, L=L, base=3, a=2)
bo = TranslationFlipBasis(k=i, p=-1, L=L, base=3, a=2)
va, ve, vo = solve(ba), solve(be), solve(bo)
for inds in Any[[1,2], [3,1], [2,4,1]]
eea = EE(va, inds, ba)
eee = EE(ve, inds, be)
eeo = EE(vo, inds, bo)
@test norm(sort(eea) - sort(vcat(eee, eeo))) ≈ 0.0 atol = 1e-7
end
end
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 3629 | include("../src/EDKit.jl")
using LinearAlgebra
using .EDKit
using Test
#---------------------------------------------------------------------------------------------------
# Tested model:
# H = ∑ᵢ rᵢ(XᵢXᵢ₊₁+YᵢYᵢ₊₁) ⟷ -i/4 ∑ᵢ 2rᵢ(ωᵢωᵢ₊ₙ₊₁ - ωᵢ₊ₙωᵢ₊₁ - ωᵢ₊ₙ₊₁ωᵢ + ωᵢ₊₁ωᵢ₊ₙ)
# Lᵢ = aᵢKᵢXᵢ + bᵢKᵢYᵢ ⟷ aᵢωᵢ + bᵢωᵢ₊ₙ
# Mᵢ = cᵢZᵢ ⟷ -i cᵢ/2 (ωᵢωᵢ₊ₙ - ωᵢ₊ₙωᵢ)
#
# Initial state:
# |ψ₀⟩ = |↑↓⋯↑↓⟩ ⟷ |10⋯10⟩
#---------------------------------------------------------------------------------------------------
function singlebody(L, r, a, b, c)
H1 = begin
mat = zeros(2L, 2L)
for i = 1:L-1
mat[i, i+1+L] = +2r[i]
mat[i+1+L, i] = -2r[i]
mat[i+1, i+L] = +2r[i]
mat[i+L, i+1] = -2r[i]
end
mat
end
L1 = begin
mat = zeros(ComplexF64, 2L, L)
for i = 1:L
mat[i, i] = a[i]
mat[i+L, i] = b[i]
end
mat
end
M1 = begin
mats = Vector{Matrix{Float64}}(undef, L)
for i = 1:L
mat = zeros(2L,2L)
mat[i, i+L] = +c[i] / 2
mat[i+L, i] = -c[i] / 2
mats[i] = mat
end
mats
end
QL = quadraticlindblad(H1, L1, M1)
Γ = begin
Z2 = [mod(i,2) for i=1:L]
covariancematrix(Z2)
end
QL, Γ
end
#---------------------------------------------------------------------------------------------------
function manybody(L, r, a, b, c)
H2 = begin
mats = [spin((r[i],"XX"), (r[i],"YY"), D=2) for i=1:L-1]
inds = [[i,i+1] for i=1:L-1]
operator(mats, inds, L) |> Array
end
L2 = begin
mats = Vector{Matrix{ComplexF64}}(undef, 2L)
for i = 1:L
Ki = if i == 1
I(1)
elseif i == 2
[-1 0; 0 1]
else
kron(fill([-1 0; 0 1], i-1)...)
end
mat = spin((a[i], "X"), (b[i], "Y"), D=2)
Ir = I(2^(L-i))
mats[i] = kron(Ki, mat, Ir)
end
for i=1:L
mats[L+i] = operator(c[i] * spin("Z"), [i], L) |> Array
end
mats
end
EL = lindblad(H2, L2)
ρ = begin
Z2 = [mod(i-1,2) for i=1:L]
ind = index(Z2)
densitymatrix(ind, L)
end
EL, ρ
end
#---------------------------------------------------------------------------------------------------
# Helper
#---------------------------------------------------------------------------------------------------
function density(dm)
L = round(Int, log(2, size(dm.ρ, 1)))
n = zeros(L)
Base.Threads.@threads for i=1:L
ni = operator([1 0;0 0], [i], L) |> Hermitian
n[i] = expectation(ni, dm)
end
n
end
#---------------------------------------------------------------------------------------------------
# main
#---------------------------------------------------------------------------------------------------
function test(steps=30)
L = 10
r, a, b, c = rand(L-1), rand(ComplexF64, L), rand(ComplexF64, L), rand(L)
# r, a, b, c = rand(L-1), rand(L), rand(L), rand(L)
QL, Γ = singlebody(L, r, a, b, c)
EL, ρ = manybody(L, r, a, b, c)
n1 = zeros(steps, L)
for i=1:steps
Γ = QL(Γ)
n1[i, :] = fermioncorrelation(Γ, 1) |> diag |> real
end
n2 = zeros(steps, L)
for i=1:steps
ρ = EL(ρ)
n2[i,:] = density(ρ)
println("Finish $i/$steps, error = $(norm(n2[i,:]-n1[i,:])).")
end
println("Total error = $(norm(n2-n1)).")
n1, n2
end
n1, n2 = test()
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 1848 | include("../src/EDKit.jl")
using LinearAlgebra
using .EDKit
using Test
#-------------------------------------------------------------------------------------------------------------------------
# Test Translational PXP
#-------------------------------------------------------------------------------------------------------------------------
@testset "Multi-threads Translational PXP" begin
L, k, p = 28, 0, 1
mat = begin
P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])
X = [0 1; 1 0]
P * kron(I(2), X, I(2)) * P
end
pxpf(v::Vector{<:Integer}) = all(v[i]==0 || v[mod(i, length(v))+1]==0 for i=1:length(v))
println("--------------------------------------")
print("Single-threads:")
@time bs = TranslationalBasis(f=pxpf, k=k, L=L, threaded=false)
print("Multi-threads :")
@time bm = TranslationalBasis(f=pxpf, k=k, L=L, threaded=true)
@test bs.I == bm.I
@test norm(bs.R-bm.R) ≈ 0.0
end
#-------------------------------------------------------------------------------------------------------------------------
# Test Translational Parity PXP
#-------------------------------------------------------------------------------------------------------------------------
@testset "Multi-threads Translational Parity PXP" begin
L, k, p = 28, 0, 1
mat = begin
P = Diagonal([1, 1, 1, 0, 1, 1, 0, 0])
X = [0 1; 1 0]
P * kron(I(2), X, I(2)) * P
end
pxpf(v::Vector{<:Integer}) = all(v[i]==0 || v[mod(i, length(v))+1]==0 for i=1:length(v))
println("--------------------------------------")
print("Single-threads:")
@time bs = TranslationParityBasis(f=pxpf, k=k, p=p, L=L, threaded=false)
print("Multi-threads :")
@time bm = TranslationParityBasis(f=pxpf, k=k, p=p, L=L, threaded=true)
@test bs.I == bm.I
@test norm(bs.R-bm.R) ≈ 0.0
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | code | 7479 | include("../src/EDKit.jl")
using Main.EDKit
using LinearAlgebra, ITensors, ITensorMPS
using Test
#----------------------------------------------------------------------------------------------------
# Basics
#----------------------------------------------------------------------------------------------------
@testset "check tensor" begin
for L in 2:5, d = 2:4
# random many-body state
v = randn(ComplexF64, d^L) |> normalize
T = EDKit.vec2tensor(v, base=d)
for i in eachindex(v)
ind = digits(i-1, base=d, pad=L) .+ 1 |> reverse
@test v[i] ≈ T[ind...]
end
end
end
#----------------------------------------------------------------------------------------------------
@testset "MPS <--> vec" begin
for L in 2:5, d = 2:4
v = randn(ComplexF64, d^L) |> normalize
T = EDKit.vec2tensor(v, base=d)
s = siteinds(d, L)
ψ = MPS(T, s)
vec = mps2vec(ψ)
for i in eachindex(v)
@test vec[i] ≈ v[i]
end
psi = vec2mps(v, s)
@test norm(psi) ≈ norm(ψ)
@test abs(inner(psi, ψ)) ≈ norm(ψ)^2
end
end
#----------------------------------------------------------------------------------------------------
@testset "op <--> mat" begin
for L in 2:5, d = 2:4
v = randn(ComplexF64, d^L) |> normalize
T = EDKit.vec2tensor(v, base=d)
s = siteinds(d, L)
ψ = MPS(T, s)
mat = Matrix(qr(randn(ComplexF64, d^2, d^2)).Q)
v2 = kron(mat, I(d^(L-2))) * v
ψ2 = apply(mat2op(mat, s[1], s[2]), ψ) |> mps2vec
@test v2 ≈ ψ2
@test op2mat(EDKit.mat2op(mat, s[1], s[2]), s[1], s[2]) ≈ mat
end
end
#----------------------------------------------------------------------------------------------------
@testset "Product MPS" begin
for L = 2:4, d=2:4
sites = siteinds(d, L)
states = [normalize(rand(d)) for i in 1:L]
v = kron(states...)
ψ = productstate(sites, states)
vec = mps2vec(ψ)
for i in eachindex(v)
@test vec[i] ≈ v[i]
end
end
end
#----------------------------------------------------------------------------------------------------
# AKLT Test
#----------------------------------------------------------------------------------------------------
λ = EDKit.λ
ITensors.op(::OpName"λ0",::SiteType"S=1") = λ(0)
ITensors.op(::OpName"λ1",::SiteType"S=1") = λ(1)
ITensors.op(::OpName"λ2",::SiteType"S=1") = λ(2)
ITensors.op(::OpName"λ3",::SiteType"S=1") = λ(3)
ITensors.op(::OpName"λ4",::SiteType"S=1") = λ(4)
ITensors.op(::OpName"λ5",::SiteType"S=1") = λ(5)
ITensors.op(::OpName"λ6",::SiteType"S=1") = λ(6)
ITensors.op(::OpName"λ7",::SiteType"S=1") = λ(7)
ITensors.op(::OpName"λ8",::SiteType"S=1") = λ(8)
ITensors.op(::OpName"++",::SiteType"S=1") = [0 0 1; 0 0 0; 0 0 0]
ITensors.op(::OpName"--",::SiteType"S=1") = [0 0 0; 0 0 0; 1 0 0]
#----------------------------------------------------------------------------------------------------
const AKLT_H2 = let h = zeros(9, 9)
h[1, 1] = h[9, 9] = 1
h[[2, 4], [2, 4]] .= 0.5
h[[6, 8], [6, 8]] .= 0.5
h[[3,5,7], [3,5,7]] .= [1; 2; 1] * [1 2 1] / 6
h
end
#----------------------------------------------------------------------------------------------------
const AKLT_TENSOR = let A = zeros(2, 2, 3)
A[1, 1, 2] = -1 / sqrt(2)
A[2, 2, 2] = 1 / sqrt(2)
A[1, 2, 1] = 1
A[2, 1, 3] = -1
A
end
#----------------------------------------------------------------------------------------------------
function aklt_mps(sites::AbstractVector; l::Int=0, r::Int=0)
tensors = if iszero(l) && iszero(r)
fill(AKLT_TENSOR, length(sites))
else
Tl = AKLT_TENSOR[[l], :, :]
Tr = AKLT_TENSOR[:, [r], :]
[Tl; fill(AKLT_TENSOR, length(sites)-2); Tr]
end
EDKit.pbcmps(sites, tensors)
end
#----------------------------------------------------------------------------------------------------
function aklt_tw(sites, k=length(sites)÷2)
L = length(sites)
os = OpSum()
for i in 1:L
os += exp(-1im * k * 2π/L * (i-1)), "++", i
end
MPO(os, sites)
end
#----------------------------------------------------------------------------------------------------
@testset "AKLT Ground State" begin
for L in 2:10
B = TranslationalBasis(L=L, N=L, k=0, base=3)
s = siteinds("S=1", L)
psi = aklt_mps(s)
ψ = mps2vec(psi, B)
@test abs(norm(ψ)-1) < 1e-5
H = trans_inv_operator(AKLT_H2, 2, B)
@test norm(H * ψ) < 1e-5
end
end
#----------------------------------------------------------------------------------------------------
@testset "AKLT Scar Tower" begin
L = 8
s = siteinds("S=1", L)
psi = aklt_mps(s)
tw = aklt_tw(s)
for j in 1:L÷2
psi = apply(tw, psi) |> normalize!
B = TranslationalBasis(L=L, N=L+2j, k=mod(j*L÷2, L), base=3)
H = trans_inv_operator(AKLT_H2, 2, B)
ψ = mps2vec(psi, B)
@test abs(norm(ψ)-1) < 1e-5
H = trans_inv_operator(AKLT_H2, 2, B)
Hψ = H * ψ
@test abs(norm(Hψ) - dot(ψ, Hψ) ) < 1e-5
end
end
#----------------------------------------------------------------------------------------------------
# Pauli Basis Test
#----------------------------------------------------------------------------------------------------
σ = EDKit.σ
@testset "Pauli Matrices" begin
name = ["1", "X", "Y", "Z"]
for L in 1:5
for i in 0:4^L-1
inds = digits(i, base=4, pad=L)
@test σ(inds) ≈ spin(prod(name[j+1] for j in inds))
end
end
end
#----------------------------------------------------------------------------------------------------
@testset "Pauli Coefficients" begin
name = ["1", "X", "Y", "Z"]
for L in 1:5
c = randn(4^L)
mat = sum(c[i] * pauli(i, L) for i in eachindex(c))
plist = pauli_list(mat)
@test plist ≈ c
end
end
#----------------------------------------------------------------------------------------------------
@testset "Lindbladian" begin
for i in 1:10
A = randn(ComplexF64, 8, 8) |> Hermitian
Ac = commutation_mat(A)
B = randn(ComplexF64, 8, 8) |> Hermitian
Bl = pauli_list(B)
C = randn(ComplexF64, 8, 8)
Cd = dissipation_mat(C)
@test pauli(Ac * Bl) ≈ -1im * (A * B - B* A)
@test pauli(Cd * Bl) ≈ C * B * C' - (C' * C * B + B * C' * C) / 2
end
end
#----------------------------------------------------------------------------------------------------
# Pauli MPS
#----------------------------------------------------------------------------------------------------
@testset "Fidelity" begin
for L in 2:7
s = siteinds("S=1/2", L)
ps = siteinds("Pauli", L)
vec = rand(ComplexF64, 2^L) |> normalize!
ρ = vec * vec'
pmps = vec2mps(pauli_list(ρ), ps)
mpo = pmps2mpo(pmps, s)
ψ = vec2mps(vec, s)
@test inner(ψ', mpo, ψ) ≈ 1.0
end
end
#----------------------------------------------------------------------------------------------------
@testset "MPS -> PMPS" begin
for L in 2:7
s = siteinds("S=1/2", L)
ps = siteinds("Pauli", L)
vec = rand(ComplexF64, 2^L) |> normalize!
ψ = vec2mps(vec, s)
pmps = mps2pmps(ψ, ps)
mpo = pmps2mpo(pmps, s)
@test inner(ψ', mpo, ψ) ≈ 1.0
end
end
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | docs | 6708 | # EDKit.jl
Julia package for general many-body exact diagonalization calculation. The package provides a general Hamiltonian constructing routine for specific symmetry sectors. The functionalities can be extended with user-defined bases.
## Installation
Run the following script in the Julia Pkg REPL environment:
```julia
pkg> add EDKit
```
Alternatively, you can install `EDKit` directly from GitHub using the following script.
```julia
pkg> add https://github.com/jayren3996/EDKit.jl
```
This is useful if you want to access the latest version of `EDKit`, which includes new features not yet registered in the Julia Pkg system but may also contain bugs.
## Examples
Instead of providing documentation, I have chosen to introduce the functionality of this package through practical calculation examples. You can find a collection of Jupyter notebooks in the [examples](https://github.com/jayren3996/EDKit.jl/tree/main/examples) folder, each showcasing various computations.
Here are a few basic examples:
### XXZ Model with Random Field
Consider the Hamiltonian
```math
H = \sum_i\left(\sigma_i^x \sigma^x_{i+1} + \sigma^y_i\sigma^y_{i+1} + h_i \sigma^z_i\sigma^z_{i+1}\right).
```
We choose the system size to be ``L=10``. The Hamiltonian needs 3 pieces of information:
1. Local operators represented by matrices;
2. Site indices where each local operator acts on;
3. Basis, if using the default tensor-product basis, only need to provide the system size.
The following script generates the information we need to generate XXZ Hamiltonian:
```julia
L = 10
mats = [
fill(spin("XX"), L);
fill(spin("YY"), L);
[randn() * spin("ZZ") for i=1:L]
]
inds = [
[[i, mod(i, L)+1] for i=1:L];
[[i, mod(i, L)+1] for i=1:L];
[[i, mod(i, L)+1] for i=1:L]
]
H = operator(mats, inds, L)
```
Then we can use the constructor `operator` to create Hamiltonian:
```julia
julia> H = operator(mats, inds, L)
Operator of size (1024, 1024) with 10 terms.
```
The constructor returns an Operator object, a linear operator that can act on vector/ matrix. For example, we can act `H` on a random state:
```julia
ψ = normalize(rand(2^L))
ψ2 = H * ψ
```
If we need a matrix representation of the Hamitonian, we can convert `H` to julia array by:
```julia
julia> Array(H)
1024×1024 Matrix{Float64}:
-1.55617 0.0 0.0 0.0 … 0.0 0.0 0.0
0.0 4.18381 2.0 0.0 0.0 0.0 0.0
0.0 2.0 -1.42438 0.0 0.0 0.0 0.0
0.0 0.0 0.0 -1.5901 0.0 0.0 0.0
0.0 0.0 2.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 2.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 0.0 0.0 2.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 0.0 -1.42438 2.0 0.0
0.0 0.0 0.0 0.0 2.0 4.18381 0.0
0.0 0.0 0.0 0.0 0.0 0.0 -1.55617
```
Or use the function `sparse` to create the sparse matrix (requires the module `SparseArrays` being imported):
```julia
julia> sparse(H)
1024×1024 SparseMatrixCSC{Float64, Int64} with 6144 stored entries:
⠻⣦⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠳⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢹⡻⣮⡳⠄⢠⡀⠀⠀⠀⠀⠀⠀⠈⠳⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠙⠎⢿⣷⡀⠙⢦⡀⠀⠀⠀⠀⠀⠀⠈⠳⣄⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠲⣄⠈⠻⣦⣄⠙⠀⠀⠀⢦⡀⠀⠀⠀⠈⠳⣄⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠈⠳⣄⠙⡻⣮⡳⡄⠀⠀⠙⢦⡀⠀⠀⠀⠈⠳⣄⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠙⠮⢻⣶⡄⠀⠀⠀⠙⢦⡀⠀⠀⠀⠈⠳⣄⠀
⢤⡀⠀⠀⠀⠀⠠⣄⠀⠀⠀⠉⠛⣤⣀⠀⠀⠀⠙⠂⠀⠀⠀⠀⠈⠓
⠀⠙⢦⡀⠀⠀⠀⠈⠳⣄⠀⠀⠀⠘⠿⣧⡲⣄⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠙⢦⡀⠀⠀⠀⠈⠳⣄⠀⠀⠘⢮⡻⣮⣄⠙⢦⡀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠙⢦⡀⠀⠀⠀⠈⠳⠀⠀⠀⣄⠙⠻⣦⡀⠙⠦⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⢦⡀⠀⠀⠀⠀⠀⠀⠈⠳⣄⠈⢿⣷⡰⣄⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢦⡀⠀⠀⠀⠀⠀⠀⠈⠃⠐⢮⡻⣮⣇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠻⣦
```
### Solving AKLT Model Using Symmetries
Consider the AKLT model
```math
H = \sum_i\left[\vec S_i \cdot \vec S_{i+1} + \frac{1}{3}\left(\vec S_i \cdot \vec S_{i+1}\right)^2\right],
```
with the system size chosen to be ``L=8``. The Hamiltonian operator for this translational-invariant Hamiltonian can be constructed using the `trans_inv_operator` function:
```julia
L = 8
SS = spin((1, "xx"), (1, "yy"), (1, "zz"), D=3)
mat = SS + 1/3 * SS^2
H = trans_inv_operator(mat, 1:2, L)
```
The second input specifies the indices the operators act on.
Because of the translational symmetry, we can simplify the problem by considering the symmetry. We construct a translational-symmetric basis by:
```julia
B = TranslationalBasis(L=8, k=0, base=3)
```
Here, `L` is the length of the system, and `k` labels the momentum ``k = 0,...,L-1`` (integer multiplies of 2π/L). The function `TranslationalBasis` returns a basis object containing 834 states. We can obtain the Hamiltonian in this sector by:
```julia
julia> H = trans_inv_operator(mat, 1:2, B)
Operator of size (834, 834) with 8 terms.
```
In addition, we can take into account the total ``S^z`` conservation, by constructing the basis
```julia
B = TranslationalBasis(L=8, N=8, k=0, base=3)
```
where the `N` is the filling number with respect to the all-spin-down state. N=L means we select those states whose total `Sz` equals 0 (note that we use 0,1,2 to label the `Sz=1,0,-1` states). This gives a further reduced Hamiltonian matrix:
```julia
julia> H = trans_inv_operator(mat, 1:2, B)
Operator of size (142, 142) with 8 terms.
```
We can go one step further by considering the spatial reflection symmetry.
```julia
B = TranslationParityBasis(L=8, N=0, k=0, p=1, base=3)
```
where the `p` argument is the parity `p = ±1`.
```julia
julia> H = trans_inv_operator(mat, 1:2, B)
Operator of size (84, 84) with 8 terms.
```
### PXP Model and Entanglement Entropy
Consider the PXP model
```math
H = \sum_i \left(P^0_{i-1} \sigma^x_i P^0_{i+1}\right).
```
Note that the model is defined on the Hilbert space where there is no local ``|↑↑⟩`` configuration. We can use the following function to check whether a product state is in the constraint subspace:
```julia
function pxpf(v::Vector{<:Integer})
for i in eachindex(v)
iszero(v[i]) && iszero(v[mod(i, length(v))+1]) && return false
end
return true
end
```
For system size ``L=20`` and in sector ``k=0,p=+1``, the Hamiltonian is constructed by:
```julia
mat = begin
P = [0 0; 0 1]
kron(P, spin("X"), P)
end
basis = TranslationParityBasis(L=20, f=pxpf, k=0, p=1)
H = trans_inv_operator(mat, 3, basis)
```
where `f` argument is the selection function for the basis state that can be user-defined. We can then diagonalize the Hamiltonian. The bipartite entanglement entropy for each eigenstate can be computed by
```julia
vals, vecs = Array(H) |> Hermitian |> eigen
EE = [ent_S(vecs[:,i], 1:L÷2, basis) for i=1:size(basis,1)]
```
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 0.4.6 | d4868b522f15a1c53ea255d8f6c97db38907674a | docs | 6955 | # Permute Basis
Based on [https://doi.org/10.1063/1.3518900]
| Basis | TrAnslation | Parity | Spin-Flip | |
| :--------------------------: | :---------: | :----: | :-------: | :--: |
| `ProjectedBasis` | ✗ | ✗ | ✗ | |
| `TranslationalBasis` | ✓ | ✗ | ✗ | |
| `ParityBasis` | ✗ | ✓ | ✗ | |
| `FlipBasis` | ✗ | ✗ | ✓ | |
| `TranslationParityBasis` | ✓ | ✓ | ✗ | |
| `TranslationFlipBasis` | ✓ | ✗ | ✓ | |
| `ParityFlipBasis` | ✗ | ✓ | ✓ | |
| `TranslationParityFlipBasis` | ✓ | ✓ | ✓ | |
## Translational Symmetry
For a periodic chain, we define the translation operator as moving the spins one step cyclically to the "right";
$$
T\left|S_1^z, \ldots, S_{L}^z\right\rangle=\left|S_{L}^z, S_1^z, \ldots, S_{L-1}^z\right\rangle
$$
We can construct momentum states $|\Psi(k)\rangle$, which by definition are eigenstates of the translation operator,
$$
T|\Psi(k)\rangle=\mathrm{e}^{i k}|\Psi(k)\rangle
$$
Here the allowed momenta are $k=2 n \pi / L$, with $n=0, \ldots, L-1$, following from the fact that $T^L=1$. States with different $k$ form their own individually diagonalizable blocks of the Hamiltonian.
### Normalization
A momentum state can be constructed using a reference state $|a\rangle$ (a single state in the $z$-component basis) and all its translations:
$$
|a(k)\rangle=\frac{1}{R_a} \sum_{r=0}^{L-1} \mathrm{e}^{-i k r} T^r|a\rangle .
$$
It can easily be verified that $T|a(k)\rangle=\mathrm{e}^{i k}|a(k)\rangle$, which is the definition of a momentum state. If all the translated states $T^r|a\rangle$ are distinct, the normalization constant is just $\sqrt{L}$. Some reference states have periodicities less than $L$, and this affects normalization. The periodicity of a state is defined as the smallest integer $N_a$ for which
$$
T^{N_a}|a\rangle=|a\rangle, \quad N_a \in\{1, \ldots, L\} .
$$
If $N_a < L$, then there are multiple copies of the same state in the sum, and the normalization constant must be modified accordingly.
> **Claim:** For given $|a\rangle$, the allowed momenta are those for which $k N_a = 2\pi m$. For the allowed momenta, the normalization constant is $R_a = L/\sqrt{N_a}$.
>
> **Proof.** The periodicity of the representative has to be compatible with the momentum in order to be a viable state. The compatibility is related to normalizability. The sum of phase factors associated with the representative state $|a\rangle$ is
> $$
> F\left(k, N_a\right)=\sum_{n=0}^{L/N_a-1} \mathrm{e}^{-i k n N_a}
> = \begin{cases}
> L / N_a, & k N_a = 2 \pi m \\
> 0, & \text { otherwise }
> \end{cases}.
> $$
> The normalization constant is then
> $$
> R_a^2=\langle a(k) | a(k)\rangle=N_a\left|F\left(k, N_a\right)\right|^2.
> $$
> Therefore, if $F\left(k, N_a\right)=0$, no state with momentum $k$ can be defined using the reference state $|a\rangle$. Thus,
> $$
> k=\frac{2 \pi}{R_a} m, \quad
> R_a = \frac{L}{\sqrt{N_a}}.
> $$
We remark that the summation in the definition of $|a(k)\rangle$ can also be written as
$$
|a(k)\rangle = \frac{1}{\sqrt{N_a}}\sum_{r=0}^{N_a-1} e^{-ikr}T^r|a\rangle.
$$
The coefficient is related to normalization $N_a^{-1/2} = R_a/L$.
### Matrix elements
Consider the translational invariant Hamiltonian $H=\sum_{j=1}^L h_j$. We need to find the state resulting when $H$ acts on the momentum states. Since $[H, T]=0$ we can write
$$
H|a(k)\rangle = \frac{1}{R_a} \sum_{r=0}^{L-1} \mathrm{e}^{-i k r} T^r H|a\rangle
= \frac{1}{R_a} \sum_{j=1}^L \sum_{r=0}^{L-1} \mathrm{e}^{-i k r} T^r h_j|a\rangle.
$$
We need to operate with the Hamiltonian operators $h_j$ only on the reference state. We can write $h_j|a\rangle= \sum_{b'}h_j(b',a)\left|b^{\prime}\right\rangle$. The prime in $\left|b^{\prime}\right\rangle$ is there to indicate that this new state is not necessarily one of the reference states used to define the basis and, therefore, a momentum state should not be written directly based on it. Provided that $\left|b^{\prime}\right\rangle$ is compatible with the momentum, there must be a reference state $\left|b\right\rangle$ which is related to it by
$$
\left|b\right\rangle=T^{l(b')}\left|b^{\prime}\right\rangle.
$$
Using this relation we have
$$
H|a(k)\rangle=\sum_{j,b'} \frac{h_j(b',a)}{R_a} \sum_{r=0}^{L-1} \mathrm{e}^{-i k r} T^{r-l(b')}\left|b_j\right\rangle
=\sum_{j,b'} h_j(b',a) \mathrm{e}^{-i k l(b')} \frac{R_{b}}{R_a}\left|b(k)\right\rangle.
$$
We thus obtain the matrix element
$$
\langle a(k)|H|b(k)\rangle = \sum_{j=1}^L\sum_{b'} h_j(b',a) \mathrm{e}^{-i k l(b')} \frac{R_{b}}{R_a}.
$$
## Reflection and Spin-Flip Symmetry
The spatial reflection operator is defined as
$$
P\left|S_1^z, \ldots, S_{L}^z\right\rangle=\left|S_{L}^z, \ldots, S_1^z\right\rangle
$$
For an eigenstate of $P|\Psi(p)\rangle=p|\Psi(p)\rangle$, where $p= \pm 1$ since $P^2=1$. We will use $T$ and $P$ for block-diagonalization, although they **cannot always be used simultaneously** because $[T, P]=0$ only in a sub-space of the Hilbert space. For a system with open boundaries, $T$ is not defined, but $P$ can be used.
For the special (and most important) case $m_z=0$ (for even $N$ ), we can block-diagonalize using a discrete subset of all the possible rotations in spin-space; the spin-flip symmetry, i.e., invariance with respect to flipping all the spins. This is defined formally by an operator we call $Z$;
$$
Z\left|S_1^z, \ldots, S_{L}^z\right\rangle=\left|-S_0^z,-S_1^z, \ldots,-S_{L}^z\right\rangle
$$
For this operator we again have $Z^2=1$ and the eigenvalues $z= \pm 1$. Since $Z$ commutes with both $P$ and $T$, it can be used together with these operators to further block-diagonalize $H$.
### States with Parity
Consider the following extension of the momentum state:
$$
|a(k, p)\rangle=\frac{1}{R_a} \sum_{r=0}^{N-1}\sum_{s=0}^1 \mathrm{e}^{-i k r}p^s T^r P^s|a\rangle,
$$
where $p= \pm 1$. Clearly, this is a state with momentum $k$, but is it also an eigenstate of $P$ with parity $p$. We can check this by explicit operation with $P$, using $P^2=1, p^2=1$, and the relationship $P T=T^{-1} P$ :
$$
P|a(k, p)\rangle =\frac{1}{R_a} \sum_{r=0}^{N-1} \mathrm{e}^{-i k r} T^{-r}(P+p)|a\rangle
= \frac{p}{R_a} \sum_{r=0}^{N-1} \mathrm{e}^{i k r} T^r(1+p P)|a\rangle .
$$
This is not exactly of the original form unless $k=0$ or $\pi$, for which $\mathrm{e}^{i k r}=\mathrm{e}^{-i k r}$. Thus, in these two special cases, parity and translational invariance can be used simultaneously for block-diagonalization and $|a(k, p)\rangle$ is indeed a momentum state with parity $p$ (or, in other words, $[T, P]=0$ in the sub-spaces with momenta $k=0$ and $\pi$ ).
### General Abelian Symmetry
The Abelian symmetry $G=Z_L\times Z_2$
| EDKit | https://github.com/jayren3996/EDKit.jl.git |
|
[
"MIT"
] | 2.2.5 | 3210de4d88af7ca5de9e26305758a59aabc48aac | code | 7089 | module PlotlyKaleido
using JSON: JSON
using Base64
using Kaleido_jll
export savefig
#-----------------------------------------------------------------------------# Kaleido Process
mutable struct Pipes
stdin::Pipe
stdout::Pipe
stderr::Pipe
proc::Base.Process
Pipes() = new()
end
const P = Pipes()
const _mathjax_url_path = "https://cdnjs.cloudflare.com/ajax/libs/mathjax"
const _mathjax_last_version = v"2.7.9"
function warn_and_kill(s::String)
@warn "$s"
kill_kaleido()
return nothing
end
kill_kaleido() = is_running() && (kill(P.proc); wait(P.proc))
is_running() = isdefined(P, :proc) && isopen(P.stdin) && process_running(P.proc)
restart(; kwargs...) = (kill_kaleido(); start(; kwargs...))
# The content of this function is inspired from https://discourse.julialang.org/t/readline-with-default-value-if-no-input-after-timeout/100388/2?u=disberd
function readline_noblock(io; timeout = 10)
msg = Channel{String}(1)
task = Task() do
try
put!(msg, readline(io))
catch
put!(msg, "Stopped")
end
end
interrupter = Task() do
sleep(timeout)
if !istaskdone(task)
Base.throwto(task, InterruptException())
end
end
schedule(interrupter)
schedule(task)
wait(task)
kaleido_version = read(joinpath(Kaleido_jll.artifact_dir, "version"), String)
out = take!(msg)
out === "Stopped" && warn_and_kill("It looks like the Kaleido process is not responding.
The unresponsive process will be killed, but this means that you will not be able to save figures using `savefig`.
If you are on Windows this might be caused by known problems with Kaleido v0.2 on Windows (you are using version $(kaleido_version)).
You might want to try forcing a downgrade of the Kaleido_jll library to 0.1.
Check the Package Readme at https://github.com/JuliaPlots/PlotlyKaleido.jl/tree/main#windows-note for more details.
If you think this is not your case, you might try using a longer timeout to check if the process is not responding (defaults to 10 seconds) by passing the desired value in seconds using the `timeout` kwarg when calling `PlotlyKaleido.start` or `PlotlyKaleido.restart`")
return out
end
function start(;
plotly_version = missing,
mathjax = missing,
mathjax_version::VersionNumber = _mathjax_last_version,
timeout = 10,
kwargs...,
)
is_running() && return
# The kaleido executable must be ran from the artifact directory
BIN = Cmd(kaleido(); dir = Kaleido_jll.artifact_dir)
# We push the mandatory plotly flag
push!(BIN.exec, "plotly")
chromium_flags = ["--disable-gpu", Sys.isapple() ? "--single-process" : "--no-sandbox"]
extra_flags = if plotly_version === missing
(; kwargs...)
else
# We create a plotlyjs flag pointing at the specified plotly version
(; plotlyjs = "https://cdn.plot.ly/plotly-$(plotly_version).min.js", kwargs...)
end
if !(mathjax === missing)
if mathjax_version > _mathjax_last_version
error(
"The given mathjax version ($(mathjax_version)) is greater than the last supported version ($(_mathjax_last_version)) of Kaleido.",
)
end
if mathjax isa Bool && mathjax
push!(
chromium_flags,
"--mathjax=$(_mathjax_url_path)/$(mathjax_version)/MathJax.js",
)
elseif mathjax isa String
# We expect the keyword argument to be a valid URL or similar, else error "Kaleido startup failed with code 1".
push!(chromium_flags, "--mathjax=$(mathjax)")
else
@warn """The value of the provided argument
mathjax=$(mathjax)
is neither a Bool nor a String and has been ignored."""
end
end
# Taken inspiration from https://github.com/plotly/Kaleido/blob/3b590b563385567f257db8ff27adae1adf77821f/repos/kaleido/py/kaleido/scopes/base.py#L116-L141
user_flags = String[]
for (k, v) in pairs(extra_flags)
flag_name = replace(string(k), "_" => "-")
if v isa Bool
v && push!(user_flags, "--$flag_name")
else
push!(user_flags, "--$flag_name=$v")
end
end
# We add the flags to the BIN
append!(BIN.exec, chromium_flags, user_flags)
kstdin = Pipe()
kstdout = Pipe()
kstderr = Pipe()
kproc =
run(pipeline(BIN, stdin = kstdin, stdout = kstdout, stderr = kstderr), wait = false)
process_running(kproc) || error("There was a problem starting up kaleido.")
close(kstdout.in)
close(kstderr.in)
close(kstdin.out)
Base.start_reading(kstderr.out)
global P
P.stdin = kstdin
P.stdout = kstdout
P.stderr = kstderr
P.proc = kproc
res = readline_noblock(P.stdout; timeout) # {"code": 0, "message": "Success", "result": null, "version": "0.2.1"}
length(res) == 0 && warn_and_kill("Kaleido startup failed.")
if is_running()
code = JSON.parse(res)["code"]
code == 0 || warn_and_kill("Kaleido startup failed with code $code.")
end
return
end
#-----------------------------------------------------------------------------# save
const ALL_FORMATS = ["png", "jpeg", "webp", "svg", "pdf", "eps", "json"]
const TEXT_FORMATS = ["svg", "json", "eps"]
function save_payload(io::IO, payload::AbstractString, format::AbstractString)
is_running() || error("It looks like the Kaleido process is not running, so you can not save plotly figures.
Remember to start the process before using `savefig` by calling `PlotlyKaleido.start()`.
If the process was killed due to an error during initialization, you will receive a warning when the `PlotlyKaleido.start` function is executing")
format in ALL_FORMATS || error("Unknown format $format. Expected one of $ALL_FORMATS")
bytes = transcode(UInt8, payload)
write(P.stdin, bytes)
write(P.stdin, transcode(UInt8, "\n"))
flush(P.stdin)
res = readline(P.stdout)
obj = JSON.parse(res)
obj["code"] == 0 || error("Transform failed: $res")
img = String(obj["result"])
# base64 decode if needed, otherwise transcode to vector of byte
bytes = format in TEXT_FORMATS ? transcode(UInt8, img) : base64decode(img)
write(io, bytes)
end
function savefig(io::IO, plot; height = 500, width = 700, scale = 1, format = "png")
payload = JSON.json((; height, width, scale, format, data = plot))
save_payload(io, payload, format)
end
function savefig(
io::IO,
plot::AbstractString;
height = 500,
width = 700,
scale = 1,
format = "png",
)
payload = "{\"width\":$width,\"height\":$height,\"scale\":$scale,\"data\": $plot}"
save_payload(io, payload, format)
end
function savefig(filename::AbstractString, plot; kw...)
format = get(kw, :format, split(filename, '.')[end])
open(io -> savefig(io, plot; format, kw...), filename, "w")
filename
end
savefig(plot, filename::AbstractString; kw...) = savefig(filename, plot; kw...)
end # module Kaleido
| PlotlyKaleido | https://github.com/JuliaPlots/PlotlyKaleido.jl.git |
|
[
"MIT"
] | 2.2.5 | 3210de4d88af7ca5de9e26305758a59aabc48aac | code | 1916 | using Test
import Pkg
if Sys.iswindows()
# Fix kaleido tests on windows due to [email protected] hanging
Pkg.add(;name = "Kaleido_jll", version = "0.1")
end
@test_nowarn @eval using PlotlyKaleido
@testset "Start" begin
if Sys.iswindows()
PlotlyKaleido.start()
else
@test_nowarn PlotlyKaleido.start()
end
@test PlotlyKaleido.is_running()
end
import PlotlyLight, EasyConfig, PlotlyJS
@testset "Saving JSON String" begin
plt = "{\"data\":{\"data\":[{\"y\":[1,2,3],\"type\":\"scatter\",\"x\":[0,1,2]}]}}"
for ext in PlotlyKaleido.ALL_FORMATS
file = tempname() * ".$ext"
open(io -> PlotlyKaleido.save_payload(io, plt, ext), file, "w")
@test isfile(file)
@test filesize(file) > 0
rm(file)
end
end
@testset "Saving Base structures" begin
plt0 = Dict(:data => [Dict(:x => [0, 1, 2], :type => "scatter", :y => [1, 2, 3])])
for plt in (plt0, NamedTuple(plt0))
for ext in PlotlyKaleido.ALL_FORMATS
ext == "eps" && continue # TODO" Why does this work above but not here?
file = tempname() * ".$ext"
PlotlyKaleido.savefig(file, plt)
@test isfile(file)
@test filesize(file) > 0
rm(file)
end
end
end
@testset "Saving PlotlyJS & PlotlyLight" begin
for plt in [
PlotlyJS.plot(PlotlyJS.scatter(x = rand(10))),
PlotlyLight.Plot(EasyConfig.Config(x = rand(10))),
]
for ext in PlotlyKaleido.ALL_FORMATS
ext == "eps" && continue # TODO" Why does this work above but not here?
file = tempname() * ".$ext"
@test PlotlyKaleido.savefig(plt, file) == file
@test isfile(file)
@test filesize(file) > 0
rm(file)
end
end
end
@testset "Shutdown" begin
PlotlyKaleido.kill_kaleido()
@test !PlotlyKaleido.is_running()
end
| PlotlyKaleido | https://github.com/JuliaPlots/PlotlyKaleido.jl.git |
|
[
"MIT"
] | 2.2.5 | 3210de4d88af7ca5de9e26305758a59aabc48aac | docs | 2194 | # PlotlyKaleido.jl
**PlotlyKaleido.jl** is for saving [Plotly.js](https://plotly.com/javascript/) plots in a variety of formats using [Kaleido](https://github.com/plotly/Kaleido).
```julia
julia> PlotlyKaleido.ALL_FORMATS
7-element Vector{String}:
"png"
"jpeg"
"webp"
"svg"
"pdf"
"eps"
"json"
```
This code was originally part of [PlotlyJS.jl](https://github.com/JuliaPlots/PlotlyJS.jl).
## Usage
```julia
using PlotlyKaleido
import PlotlyLight, EasyConfig, PlotlyJS
PlotlyKaleido.start() # start Kaleido server
p1 = PlotlyLight.Plot(EasyConfig.Config(x = rand(10)))
p2 = PlotlyJS.plot(PlotlyJS.scatter(x = rand(10)))
# PlotlyKaleido is agnostic about which package you use to make Plotly plots!
PlotlyKaleido.savefig(p1, "plot1.png")
PlotlyKaleido.savefig(p2, "plot2.png")
```
If needed, you can restart the server:
```julia
PlotlyKaleido.restart()
```
or simply kill it:
```julia
PlotlyKaleido.kill_kaleido()
```
To enable LaTeX (using MathJax v2) in plots, use the keyword argument `mathjax`:
```julia
PlotlyKaleido.start(mathjax=true) # start Kaleido server with MathJax enabled
```
## Windows Note
Many people on Windows have issues with the latest (0.2.1) version of the Kaleido library (see for example [discourse](https://discourse.julialang.org/t/plotlyjs-causes-errors-cant-figure-out-how-to-use-plotlylight-how-to-use-plotly-from-julia/108853/29), [this PR's comment](https://github.com/JuliaPlots/PlotlyKaleido.jl/pull/17#issuecomment-1969325440) and [this issue](https://github.com/plotly/Kaleido/issues/134) on the Kaleido repository).
Many people have succesfully fixed this problem on windows by downgrading the kaleido library to version 0.1.0 (see [the previously mentioned issue](https://github.com/plotly/Kaleido/issues/134)). If you experience issues with `PlotlyKaleido.start()` hanging on windows, you may want try adding `[email protected]` explicitly to your project environment to fix this. You can do so by either doing:
```julia
add [email protected]
```
inside the REPL package enviornment, or by calling the following code in the REPL directly:
```julia
begin
import Pkg
Pkg.add(; name = "Kaleido_jll", version = "0.1")
end
```
| PlotlyKaleido | https://github.com/JuliaPlots/PlotlyKaleido.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | code | 948 | using CirculatorySystemModels
using Documenter
DocMeta.setdocmeta!(CirculatorySystemModels, :DocTestSetup, :(using CirculatorySystemModels); recursive=true)
makedocs(;
modules=[CirculatorySystemModels],
authors="TS-CUBED <[email protected]> and contributors",
repo="https://github.com/TS-CUBED/CirculatorySystemModels.jl/blob/{commit}{path}#{line}",
sitename="CirculatorySystemModels.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://TS-CUBED.github.io/CirculatorySystemModels.jl",
edit_link="main",
assets=String[]
),
pages=[
"Home" => "index.md",
"Examples" => [
"Bjørdalsbakke - Simple Single-Chamber CV-Circuit" => "examples/BjordalsbakkeModel.md"
],
"Method Index" => "autodoc.md",
]
)
deploydocs(;
repo="github.com/TS-CUBED/CirculatorySystemModels.jl",
devbranch="main"
)
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | code | 7521 | ## # Importing the required packages
using CirculatorySystemModels
using ModelingToolkit
using OrdinaryDiffEq
using Plots
using DisplayAs
# # A simple single-chamber model
#
# 
#
#
# This follows Bjørdalsbakke et al.
#
# Bjørdalsbakke, N.L., Sturdy, J.T., Hose, D.R., Hellevik, L.R., 2022. Parameter estimation for closed-loop lumped parameter models of the systemic circulation using synthetic data. Mathematical Biosciences 343, 108731. https://doi.org/10.1016/j.mbs.2021.108731
#
#
# Changes from the published version above:
#
# - Capacitors are replaced by compliances. These are identical to capacitors, but have an additional parameter, the unstrained volume $V_0$, which allows for realistic blood volume modelling.
# Compliances have an inlet and an oulet in line with the flow, rather than the ground connector of the dangling capacitor.
# - The aortic resistor is combined with the valve (diode) in the `ResistorDiode` element.
#
# [Jupyter Notebook](./BjordalsbakkeModel.ipynb)
# ## Define the parameters
#
# All the parameters are taken from table 1 of [Bjørdalsbakke2022].
#
# Cycle time in seconds
##
τ = 0.85
# Double Hill parameters for the ventricle
#
Eₘᵢₙ = 0.03
Eₘₐₓ = 1.5
n1LV = 1.32;
n2LV = 21.9;
Tau1fLV = 0.303 * τ;
Tau2fLV = 0.508 * τ
##
# Resistances and Compliances
#
R_s = 1.11
C_sa = 1.13
C_sv = 11.0
# Valve parameters
#
# Aortic valve basic
Zao = 0.033
# Mitral valve basic
Rmv = 0.006
## Inital Pressure (mean cardiac filling pressure)
MCFP = 7.0
### Calculating the additional `k` parameter
#
# The ventricle elastance is modelled as:
#
# $$E_{l v}(t)=\left(E_{\max }-E_{\min }\right) e(t)+E_{\min }$$
#
# where $e$ is a double-Hill function, i.e., two Hill-functions, which are multiplied by each other:
#
# $$e(\tau)= k \times \frac{\left(\tau / \tau_1\right)^{n_1}}{1+\left(\tau / \tau_1\right)^{n_1}} \times \frac{1}{1+\left(\tau / \tau_2\right)^{n_2}}$$
#
# and $k$ is a scaling factor to assure that $e(t)$ has a maximum of $e(t)_{max} = 1$:
#
# $$k = \max \left(\frac{\left(\tau / \tau_1\right)^{n_1}}{1+\left(\tau / \tau_1\right)^{n_1}} \times \frac{1}{1+\left(\tau / \tau_2\right)^{n_2}} \right)^{-1}$$
#
nstep = 1000
t = LinRange(0, τ, nstep)
kLV = 1 / maximum((t ./ Tau1fLV).^n1LV ./ (1 .+ (t ./ Tau1fLV).^n1LV) .* 1 ./ (1 .+ (t ./ Tau2fLV).^n2LV))
# ## Set up the model elements
#
# Set up time as a variable `t`
#
@variables t
# Heart is modelled as a single chamber (we call it `LV` for "Left Ventricle" so the model can be extended later, if required):
#
@named LV = DHChamber(V₀ = 0.0, Eₘₐₓ=Eₘₐₓ, Eₘᵢₙ=Eₘᵢₙ, n₁=n1LV, n₂=n2LV, τ = τ, τ₁=Tau1fLV, τ₂=Tau2fLV, k = kLV, Eshift=0.0)
# The two valves are simple diodes with a small resistance
# (resistance is needed, since perfect diodes would connect two elastances/compliances, which will lead to unstable oscillations):
#
@named AV = ResistorDiode(R=Zao)
@named MV = ResistorDiode(R=Rmv)
# The main components of the circuit are 1 resistor `Rs` and two compliances for systemic arteries `Csa`,
# and systemic veins `Csv` (names are arbitrary).
# _Note: one of the compliances is defined in terms of $dV/dt$ using the option `inV = true`. The other
# without that option is in $dp/dt$._
#
@named Rs = Resistor(R=R_s)
@named Csa = Compliance(C=C_sa)
@named Csv = Compliance(C=C_sv, inP=true)
# ## Build the system
#
# ### Connections
#
# The system is built using the `connect` function. `connect` sets up the Kirchhoff laws:
#
# - pressures are the same in all connected branches on a connector
# - sum of all flow rates at a connector is zero
#
# The resulting set of Kirchhoff equations is stored in `circ_eqs`:
#
circ_eqs = [
connect(LV.out, AV.in)
connect(AV.out, Csa.in)
connect(Csa.out, Rs.in)
connect(Rs.out, Csv.in)
connect(Csv.out, MV.in)
connect(MV.out, LV.in)
]
# ### Add the component equations
#
# In a second step, the system of Kirchhoff equations is completed by the component equations (both ODEs and AEs), resulting in the full, overdefined ODE set `circ_model`.
#
# _Note: we do this in two steps._
#
@named _circ_model = ODESystem(circ_eqs, t)
@named circ_model = compose(_circ_model,
[LV, AV, MV, Rs, Csa, Csv])
# ### Simplify the ODE system
#
# The crucial step in any acausal modelling is the sympification and reduction of the OD(A)E system to the minimal set of equations. ModelingToolkit.jl does this in the `structural_simplify` function.
#
circ_sys = structural_simplify(circ_model)
# `circ_sys` is now the minimal system of equations. In this case it consists of 3 ODEs for the ventricular volume and the systemic and venous pressures.
#
# _Note: this reduces and optimises the ODE system. It is, therefore, not always obvious, which states it will use and which it will drop. We can use the `states` and `observed` function to check this. It is recommended to do this, since small changes can reorder states, observables, and parameters._
#
# States in the system are now:
unknowns(circ_sys)
# Observed variables - the system will drop these from the ODE system that is solved, but it keeps all the algebraic equations needed to calculate them in the system object, as well as the `ODEProblem` and solution object - are:
observed(circ_sys)
# And the parameters (these could be reordered, so check these, too):
parameters(circ_sys)
# ### Define the ODE problem
#
# First defined initial conditions `u0` and the time span for simulation:
#
# _Note: the initial conditions are defined as a parameter map, rather than a vector, since the parameter map allows for changes in order.
# This map can include non-existant states (like `LV.p` in this case), which allows for exchanging the compliances or the ventricle
# for one that's defined in terms of $dp/dt$)._
u0 = [
LV.p => MCFP
LV.V => MCFP/Eₘᵢₙ
Csa.p => MCFP
Csa.V => MCFP*C_sa
Csv.p => MCFP
Csv.V => MCFP*C_sv
]
#
tspan = (0, 20)
# in this case we use the mean cardiac filling pressure as initial condition, and simulate 20 seconds.
#
# Then we can define the problem:
#
prob = ODEProblem(circ_sys, u0, tspan)
# ## Simulate
#
# The ODE problem is now in the MTK/DifferentialEquations.jl format and we can use any DifferentialEquations.jl solver to solve it:
#
sol = solve(prob, Vern7(), reltol=1e-12, abstol=1e-12);
# ## Results
p1 = plot(sol, idxs=[LV.p, Csa.in.p], tspan=(16 * τ, 17 * τ), xlabel = "Time [s]", ylabel = "Pressure [mmHg]", hidexaxis = nothing) # Make a line plot
p2 = plot(sol, idxs=[LV.V], tspan=(16 * τ, 17 * τ),xlabel = "Time [s]", ylabel = "Volume [ml]", linkaxes = :all)
p3 = plot(sol, idxs=[Csa.in.q,Csv.in.q], tspan=(16 * τ, 17 * τ),xlabel = "Time [s]", ylabel = "Flow rate [ml/s]", linkaxes = :all)
p4 = plot(sol, idxs=(LV.V, LV.p), tspan=(16 * τ, 17 * τ),xlabel = "Volume [ml]", ylabel = "Pressure [mmHg]", linkaxes = :all)
img = plot(p1, p2, p3, p4; layout=@layout([a b; c d]), legend = true)
img = DisplayAs.Text(DisplayAs.PNG(img))
img
##
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | code | 49704 | module CirculatorySystemModels
using ModelingToolkit
export Pin, OnePort, Ground, Resistor, QResistor, PoiseuilleResistor, Capacitor, Inductance, Compliance, Elastance, VariableElastance, ConstantPressure, ConstantFlow, DrivenPressure, DrivenFlow, DHChamber, ShiChamber, ShiAtrium, ShiHeart, WK3, WK3E, CR, CRL, RRCR, ShiSystemicLoop, ShiPulmonaryLoop, ResistorDiode, OrificeValve, ShiValve, MynardValve_SemiLunar, MynardValve_Atrioventricular
@parameters t
D = Differential(t)
@connector Pin begin
p(t)
q(t), [connect = Flow]
end
@mtkmodel Ground begin
@components begin
g = Pin()
end
@parameters begin
P = 0.0
end
@equations begin
g.p ~ P
end
end
@mtkmodel OnePort begin
@components begin
out = Pin()
in = Pin()
end
@variables begin
Δp(t)
q(t)
end
@equations begin
Δp ~ out.p - in.p
0 ~ in.q + out.q
q ~ in.q
end
end
@mtkmodel OnePortWithExtPressure begin
@components begin
out = Pin()
in = Pin()
ep = Pin()
end
@variables begin
Δp(t)
q(t)
pg(t)
end
@equations begin
Δp ~ out.p - in.p
0 ~ in.q + out.q
0 ~ ep.q
q ~ in.q
pg ~ p - ep.p
end
end
"""
`Resistor(;name, R=1.0)`
Implements the resistor using Ohm's law to represent a vessels linear resistance to blood flow.
Parameter is in the cm, g, s system.
Pressure in mmHg.
`Δp` is calculated in mmHg
`q` calculated in cm^3/s (ml/s)
Named parameters:
`R`: Resistance of the vessel to the fluid in mmHg*s/ml
"""
@mtkmodel Resistor begin
@extend OnePort()
@parameters begin
R = 1.0
end
@equations begin
Δp ~ -q * R
end
end
"""
`QResistor(;name, K=1.0)`
Implements the quadratic resistor to represent a vessels non-linear resistance to blood flow.
Parameters are in the cm, g, s system.
Pressures in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`K`: non-linear resistance of the vessel to the fluid in mmHg*s^2/ml^2
"""
@mtkmodel QResistor begin
@extend OnePort()
@parameters begin
K = 1.0
end
@equations begin
Δp ~ -q * abs(q) * K
end
end
"""
`Capacitor(;name, C=1.0)`
Implements a capacitor to represent vessel capacitance.
Parameters are in the cm, g, s system.
Pressures in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`C`: capacitance of the vessel in ml/mmHg
"""
@mtkmodel Capacitor begin
@extend OnePort()
@parameters begin
C = 1.0
end
@equations begin
D(Δp) ~ -q / C
end
end
"""
`Inductance(;name, L=1.0)`
Implements the inductance to represent blood inertance.
Parameters are in the cm, g, s system.
Pressures in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`L`: Inertia of the fluid in mmHg*s^2/ml
"""
@mtkmodel Inductance begin
@extend OnePort()
@parameters begin
L = 1.0
end
@equations begin
D(q) ~ -Δp / L
end
end
"""
`PoiseuilleResistor(;name, μ=3e-2, r=0.5, L=5)`
Implements the resistance following the Poiseuille law.
Parameters are in the cm, g, s system.
Pressures in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`μ`: viscosity of fluid in dyne s / cm^2
`r`: radius of vessel segmenty in cm
`L`: length of vessel segment in cm
"""
@mtkmodel PoiseuilleResistor begin
@extend OnePort()
@parameters begin
μ = 3e-2
r = 0.1
L = 1
end
begin
R = 8 * μ * L / (π * r^4) * (1 / 1333.2)
end
@equations begin
Δp ~ -q * R
end
end
"""
`Compliance(; name, V₀=0.0, C=1.0, inP=false, has_ep=false, has_variable_ep=false, p₀=0.0)`
Implements the compliance of a vessel.
Parameters are in the cm, g, s system.
Pressure in mmHg.
`p` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`V₀`: Unstressed volume ml
`C`: Vessel compliance in ml/mmHg
`inP`: (Bool) formulate in dp/dt (default: false)
`has_ep`: (Bool) if true, add a parameter `p₀` for pressure offset
e.g., for thoracic pressure (default: false)
`p₀`: External pressure in mmHg (e.g., thorax pressure, default: 0.0)
_Note: if this argument is set, it will be used, even if `has_ep` is
`false`. `has_ep` only controls if `p₀` will be exposed as a parameter!_
has_variable_ep`: (Bool) expose pin for variable external pressure (default: false)
This pin can be connected to another pin or function providing external pressure.
_Note: if `has_variable_ep` is set to `true` this pin is created, independent of
`has_ep`!_
"""
@component function Compliance(; name, V₀=0.0, C=1.0, inP=false, has_ep=false, has_variable_ep=false, p₀=0.0)
@named in = Pin()
@named out = Pin()
if has_variable_ep
@named ep = Pin()
end
sts = @variables begin
V(t)
p(t)
end
ps = @parameters begin
V₀ = V₀
C = C
end
# Add the thoracic pressure variant
D = Differential(t)
eqs = [
0 ~ in.p - out.p
p ~ in.p
]
if has_variable_ep
push!(sts,
(@variables p_rel(t))[1]
)
if has_ep
push!(ps,
(@parameters p₀ = p₀)[1]
)
end
push!(eqs,
p_rel ~ ep.p + p₀,
ep.q ~ 0
)
elseif has_ep
push!(ps,
(@parameters p₀ = p₀)[1]
)
p_rel = p₀
else
p_rel = p₀
end
if inP
push!(eqs,
V ~ (p - p_rel) * C + V₀,
D(p) ~ (in.q + out.q) * 1 / C
)
else
push!(eqs,
p ~ (V - V₀) / C + p_rel,
D(V) ~ in.q + out.q
)
end
if has_variable_ep
compose(ODESystem(eqs, t, sts, ps; name=name), in, out, ep)
else
compose(ODESystem(eqs, t, sts, ps; name=name), in, out)
end
end
"""
`Elastance(; name, V₀=0.0, E=1.0, inP=false, has_ep=false, has_variable_ep=false, p₀=0.0)`
Implements the elastance of a vessel. Elastance more commonly used to describe the heart.
Parameters are in the cm, g, s system.
Pressure in mmHg.
`p` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`V₀`: Unstressed volume ml
`E`: Vessel elastance in ml/mmHg. Equivalent to compliance as E=1/C
`inP`: (Bool) formulate in dp/dt (default: false)
`has_ep`: (Bool) if true, add a parameter `p₀` for pressure offset
e.g., for thoracic pressure (default: false)
`p₀`: External pressure in mmHg (e.g., thorax pressure, default: 0.0)
_Note: if this argument is set, it will be used, even if `has_ep` is
`false`. `has_ep` only controls if `p₀` will be exposed as a parameter!_
has_variable_ep`: (Bool) expose pin for variable external pressure (default: false)
This pin can be connected to another pin or function providing external pressure.
_Note: if `has_variable_ep` is set to `true` this pin is created, independent of
`has_ep`!_
"""
@component function Elastance(; name, V₀=0.0, E=1.0, inP=false, has_ep=false, has_variable_ep=false, p₀=0.0)
@named in = Pin()
@named out = Pin()
if has_variable_ep
@named ep = Pin()
end
sts = @variables begin
V(t)
p(t)
end
ps = @parameters begin
V₀ = V₀
E = E
end
D = Differential(t)
eqs = [
0 ~ in.p - out.p
p ~ in.p
]
if has_variable_ep
push!(sts,
(@variables p_rel(t))[1]
)
if has_ep
push!(ps,
(@parameters p₀ = p₀)[1]
)
end
push!(eqs,
p_rel ~ ep.p + p₀,
ep.q ~ 0
)
elseif has_ep
push!(ps,
(@parameters p₀ = p₀)[1]
)
p_rel = p₀
else
p_rel = p₀
end
if inP
push!(eqs,
V ~ (p - p_rel) / E + V₀,
D(p) ~ (in.q + out.q) * E
)
else
push!(eqs,
p ~ (V - V₀) * E + p_rel,
D(V) ~ in.q + out.q
)
end
if has_variable_ep
compose(ODESystem(eqs, t, sts, ps; name=name), in, out, ep)
else
compose(ODESystem(eqs, t, sts, ps; name=name), in, out)
end
end
"""
`VariableElastance(; name, V₀=0.0, C=1.0, Escale=1.0, fun, inP=false, has_ep=false, has_variable_ep=false, p₀=0.0)`
`VariableElastance` is defined based on the `Elastance` element,
but has a time varying elastance function modelling
the contraction of muscle fibres.
Named parameters:
`V₀`: stress-free volume (zero pressure volume)
`Escale`: scaling factor (elastance factor)
`fun`: function object for elastance (must be `fun(t)`)
`inP`: (Bool) formulate in dp/dt (default: false)
`has_ep`: (Bool) if true, add a parameter `p₀` for pressure offset
e.g., for thoracic pressure (default: false)
`p₀`: External pressure in mmHg (e.g., thorax pressure, default: 0.0)
_Note: if this argument is set, it will be used, even if `has_ep` is
`false`. `has_ep` only controls if `p₀` will be exposed as a parameter!_
has_variable_ep`: (Bool) expose pin for variable external pressure (default: false)
This pin can be connected to another pin or function providing external pressure.
_Note: if `has_variable_ep` is set to `true` this pin is created, independent of
`has_ep`!_
"""
@component function VariableElastance(; name, V₀=0.0, C=1.0, Escale=1.0, fun, inP=false, has_ep=false, has_variable_ep=false, p₀=0.0)
@named in = Pin()
@named out = Pin()
if has_variable_ep
@named ep = Pin()
end
sts = @variables begin
V(t)
p(t)
end
ps = @parameters begin
V₀ = V₀
C = C
end
D = Differential(t)
E = Escale * fun(t)
eqs = [
0 ~ in.p - out.p
p ~ in.p
]
if has_variable_ep
push!(sts,
(@variables p_rel(t))[1]
)
push!(eqs,
p_rel ~ ep.p,
ep.q ~ 0
)
elseif has_ep
push!(ps,
(@parameters p₀ = p₀)[1]
)
p_rel = p₀
else
p_rel = p₀
end
if inP
push!(eqs,
V ~ (p - p_rel) / E + V₀,
D(p) ~ (in.q + out.q) * E + V * D(E(t))
)
else
push!(eqs,
p ~ (V - V₀) * E + p_rel,
D(V) ~ in.q + out.q
)
end
if has_variable_ep
compose(ODESystem(eqs, t, sts, ps; name=name), in, out, ep)
else
compose(ODESystem(eqs, t, sts, ps; name=name), in, out)
end
end
"""
`ConstantPressure(;name, P=1.0)`
Implements a constant pressure source to a system.
Parameters are in the cm, g, s system.
Pressure in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`P`: Constant pressure in mmHg
"""
@mtkmodel ConstantPressure begin
@extend OnePort()
@parameters begin
P = 1.0
end
@equations begin
Δp ~ P
end
end
"""
`ConstantFlow(;name, Q=1.0)`
Implements a constant flow source to a system.
Parameters are in the cm, g, s system.
Pressure in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`Q`: Constant flow in cm^3/s (ml/s)
"""
@mtkmodel ConstantFlow begin
@extend OnePort()
@parameters begin
Q = 1.0
end
@equations begin
q ~ Q
end
end
"""
`DrivenPressure(; name, fun, P=1.0)`
Implements a driven pressure source to a system modulated by a function provided.
Parameters are in the cm, g, s system.
Pressure in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`P`: Constant pressure in mmHg
`fun`: Function which modulates the input
"""
@mtkmodel DrivenPressure begin
@extend OnePort()
@structural_parameters begin
fun = sin
end
@parameters begin
P = 1.0
end
@equations begin
Δp ~ P * fun(t)
end
end
"""
`DrivenFlow(; name, fun, Q=1.0)`
Implements a driven flow source to a system.
Parameters are in the cm, g, s system.
Pressure in mmHg.
`Δp` is calculated in mmHg,
`q` is calculated in cm^3/s (ml/s).
Named parameters:
`Q`: Constant flow in cm^3/s (ml/s).
`τ` Length of cardiac cycle is s
`fun`: Function which modulates the input
"""
@mtkmodel DrivenFlow begin
@extend OnePort()
@structural_parameters begin
fun = sin
end
@parameters begin
Q = 1.0
end
@equations begin
q ~ Q * fun(t)
end
end
"""
`DHChamber(;name, V₀, Eₘᵢₙ, n₁, n₂, τ, τ₁, τ₂, k, Eshift=0.0, inP=false)`
The Double Hill chamber/ventricle model is defined based on the vessel
element, but has a time varying elastance function modelling the contraction
of muscle fibres
The time varying elastance is calculated using the Double Hill model.
This model uses external helper functions `elastance` and `delastance`
which describe the elastance function and the first derivative of it.
It calculates the elastance as:
E(t) = (Eₘₐₓ - Eₘᵢₙ) * e(t) + Eₘᵢₙ
where e(t) is the Double-Hill function.
Named parameters:
`V₀`: stress-free volume (zero pressure volume)
`p₀` pressure offset (defaults to zero)
this is present in some papers (e.g. Shi), so is
provided here for conformity. Defaults to 0.0
`Eₘᵢₙ`: minimum elastance
`Eₘₐₓ`: maximum elastance
`n₁`: rise coefficient
`n₂`: fall coefficient
`τ`: pulse length [s]
`τ₁`: rise timing parameter[s]
`τ₂`: fall timimg paramter [s]
`k`: elastance factor*
`Eshift`: time shift of contraction (for atria)
`inP`: (Bool) formulate in dp/dt (default: false)
*Note: `k` is not an independent parameter, it is a scaling factor that corresponds
to 1/max(e(t)), which ensures that e(t) varies between zero and 1.0, such that
E(t) varies between Eₘᵢₙ and Eₘₐₓ.
"""
@mtkmodel DHChamber begin
@components begin
in = Pin()
out = Pin()
end
@structural_parameters begin
inP = false
end
@variables begin
V(t)
p(t)
end
@parameters begin
V₀
p₀ = 0.0
Eₘᵢₙ
Eₘₐₓ
n₁
n₂
τ
τ₁
τ₂
k
Eshift = 0.0
end
begin
E = DHelastance(t, Eₘᵢₙ, Eₘₐₓ, n₁, n₂, τ, τ₁, τ₂, Eshift, k)
DE = DHdelastance(t, Eₘᵢₙ, Eₘₐₓ, n₁, n₂, τ, τ₁, τ₂, Eshift, k)
p_rel = p₀
end
@equations begin
0 ~ in.p - out.p
p ~ in.p
if inP
V ~ (p - p_rel) / E + V₀
D(p) ~ (in.q + out.q) * E + (p - p_rel) / E * DE
else
p ~ (V - V₀) * E + p_rel
D(V) ~ in.q + out.q
end
end
end
"""
`DHelastance(t, Eₘᵢₙ, Eₘₐₓ, n₁, n₂, τ, τ₁, τ₂, Eshift, k)`
Helper function for `DHChamber`
"""
function DHelastance(t, Eₘᵢₙ, Eₘₐₓ, n₁, n₂, τ, τ₁, τ₂, Eshift, k)
tᵢ = rem(t + (1 - Eshift) * τ, τ)
return (Eₘₐₓ - Eₘᵢₙ) * k * ((tᵢ / τ₁)^n₁ / (1 + (tᵢ / τ₁)^n₁)) * (1 / (1 + (tᵢ / τ₂)^n₂)) + Eₘᵢₙ
end
"""
`DHdelastance(t, Eₘᵢₙ, Eₘₐₓ, n₁, n₂, τ, τ₁, τ₂, Eshift, k)`
Helper function for `DHChamber`
"""
function DHdelastance(t, Eₘᵢₙ, Eₘₐₓ, n₁, n₂, τ, τ₁, τ₂, Eshift, k)
tᵢ = rem(t + (1 - Eshift) * τ, τ)
de = ((Eₘₐₓ - Eₘᵢₙ) * k * (τ₂^n₂ * n₁ * tᵢ^(n₁ - 1) *
(τ₁^n₁ * τ₂^n₂ + τ₁^n₁ * tᵢ^n₂ + τ₂^n₂ * tᵢ^n₁ + tᵢ^(n₁ + n₂)) -
τ₂^n₂ * tᵢ^n₁ * (τ₁^n₁ * n₂ * tᵢ^(n₂ - 1) + τ₂^n₂ * n₁ * tᵢ^(n₁ - 1) +
(n₁ + n₂) * tᵢ^(n₁ + n₂ - 1))) /
(τ₁^n₁ * τ₂^n₂ + τ₁^n₁ * tᵢ^n₂ + τ₂^n₂ * tᵢ^n₁ + tᵢ^(n₁ + n₂))^2)
return de
end
"""
`ShiChamber(;name, V₀, p₀=0.0, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift=0.0)`
Implemention of a ventricle following Shi/Korakianitis.
This model uses external helper function `shiElastance`
which describes the elastance function.
Named parameters:
`V₀` stress-free volume (zero pressure volume)
`p₀` pressure offset (defaults to zero)
this is present in the original paper, so is
provided here for conformity. Defaults to 0.0
`Eₘᵢₙ` minimum elastance
`τ` pulse length
`τₑₛ` end systolic time (end of rising cosine)
`τₑₚ` end pulse time (end of falling cosine)
`Eshift`: time shift of contraction (for atria), set to `0` for ventricle
`inP`: (Bool) formulate in dp/dt (default: false)
"""
@mtkmodel ShiChamber begin
@structural_parameters begin
inP = false
end
@variables begin
V(t)
p(t)
end
@parameters begin
V₀
p₀ = 0.0
Eₘᵢₙ
Eₘₐₓ
τ
τₑₛ
τₑₚ
Eshift
end
@components begin
in = Pin()
out = Pin()
end
begin
E = ShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
DE = DShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
p_rel = p₀
end
@equations begin
0 ~ in.p - out.p
p ~ in.p
if inP
V ~ (p - p_rel) / E + V₀
D(p) ~ (in.q + out.q) * E + (p - p_rel) / E * DE
else
p ~ (V - V₀) * E + p_rel
D(V) ~ in.q + out.q
end
end
end
"""
`ShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)`
Elastance function `E(t)` for ventricle simulation based on Shi's
double cosine function.
Parameters:
`Eₘᵢₙ`: minimum elastance (diastole)
`Eₘₐₓ`: maximum elastance (systole)
`τₑₛ`: end systolic time (end of rising cosine)
`τₑₚ`: end of pulse time (end of falling cosine)
`Eshift`: time shift of contraction (for atria), set to `0` for ventricle
"""
function ShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
tᵢ = rem(t + (1 - Eshift) * τ, τ)
Eₚ = (tᵢ <= τₑₛ) * (1 - cos(tᵢ / τₑₛ * pi)) / 2 +
(tᵢ > τₑₛ) * (tᵢ <= τₑₚ) * (1 + cos((tᵢ - τₑₛ) / (τₑₚ - τₑₛ) * pi)) / 2 +
(tᵢ <= τₑₚ) * 0
E = Eₘᵢₙ + (Eₘₐₓ - Eₘᵢₙ) * Eₚ
return E
end
"""
DShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
Helper function for `ShiChamber`
Derivative of the elastance function `E(t)` for ventricle simulation based on Shi's
double cosine function.
Parameters:
`Eₘᵢₙ`: minimum elastance (diastole)
`Eₘₐₓ`: maximum elastance (systole)
`τₑₛ`: end systolic time (end of rising cosine)
`τₑₚ`: end of pulse time (end of falling cosine)
`Eshift`: time shift of contraction (for atria), set to `0` for ventricle
"""
function DShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
tᵢ = rem(t + (1 - Eshift) * τ, τ)
DEₚ = (tᵢ <= τₑₛ) * pi / τₑₛ * sin(tᵢ / τₑₛ * pi) / 2 +
(tᵢ > τₑₛ) * (tᵢ <= τₑₚ) * pi / (τₑₚ - τₑₛ) * sin((τₑₛ - tᵢ) / (τₑₚ - τₑₛ) * pi) / 2
(tᵢ <= τₑₚ) * 0
DE = (Eₘₐₓ - Eₘᵢₙ) * DEₚ
return DE
end
"""
`ShiAtrium(;name, V₀, p₀, Eₘᵢₙ, Eₘₐₓ, τ, τpwb, τpww, inP = false)`
Implementation of the Atrium following Shi/Korakianitis.
Named parameters:
name name of the element
`V₀` Unstressed chamber volume in ml
`p₀` Unstressed chamber pressure in mmHg
`Eₘᵢₙ` Minimum elastance (diastole) in mmHg/ml
`Eₘₐₓ` Maximum elastance (systole) in mmHg/ml
`τ` Length of cardiac cycle in s
`τpwb` Atrial contraction time in s
`τpww` Atrial offset time in s
"""
@mtkmodel ShiAtrium begin
@components begin
in = Pin()
out = Pin()
end
@variables begin
V(t)
p(t)
end
@structural_parameters begin
inP = false
end
@parameters begin
V₀
p₀
Eₘᵢₙ
Eₘₐₓ
τ
τpwb
τpww
end
begin
# adjust timing parameters to fit the elastance functions for the ventricle
# define elastance based on ventricle E function
E = ShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, 0.5 * τpww, τpww, τpwb)
DE = DShiElastance(t, Eₘᵢₙ, Eₘₐₓ, τ, 0.5 * τpww, τpww, τpwb)
p_rel = p₀
end
@equations begin
0 ~ in.p - out.p
p ~ in.p
if inP
V ~ (p - p_rel) / E + V₀
D(p) ~ (in.q + out.q) * E + (p - p_rel) / E * DE
else
p ~ (V - V₀) * E + p_rel
D(V) ~ in.q + out.q
end
end
end
"""
`ShiHeart(; name, τ, LV.V₀, LV.p0, LV.Emin, LV.Emax, LV.τes, LV.τed, LV.Eshift,
RV.V₀, RV.p0, RV.Eₘᵢₙ, RV.Eₘₐₓ, RV.τes, RV.τed, RV.Eshift, LA.V₀, LA_p0,
LA.Emin, LA.Emax, LA.τes, LA.τed, LA.Eshift, RA.V₀, RA.p0, RA.Emin,
RA.Emax, RA.τes, RA.τed, RA.Eshift, AV.CQ, AV.Kp, AV.Kf, AV.Kb, AV.Kv,
AV.θmax, AV.θmin, PV.CQ, PV.Kp, PV.Kf, PV.Kb, PV.Kv, PV.θmax, PV.θmin,
MV.CQ, MV.Kp, MV.Kf, MV.Kb, MV.Kv, MV.θmax, MV.θmin, TV.CQ, TV.Kp, TV.Kf,
TV.Kb, TV.Kv, TV.θmax, TV.θmin)`
Models a whole heart, made up of 2 ventricles (Left & Right Ventricle) and 2 atria (Left & Right atrium)
created from the ShiChamber element. Includes the 4 corresponding valves (Aortic, Mitral, Pulmonary and Tricuspid valve) created using the ShiValve element.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s).
Maximum and Minimum angles given in rad, to convert from degrees multiply angle by pi/180.
Named parameters:
`τ` Length of the cardiac cycle in s
`LV_V₀` Unstressed left ventricular volume in ml
`LV_p0` Unstressed left ventricular pressure in mmHg
`LV_Emin` Minimum left ventricular elastance (diastole) in mmHg/ml
`LV_Emax` Maximum left ventricular elastance (systole) in mmHg/ml
`LV_τes` Left ventricular end systolic time in s
`LV_τed` Left ventricular end distolic time in s
`LV_Eshift` Shift time of contraction - 0 for left ventricle
`RV_V₀` Unstressed right ventricular volume in ml
`RV_p0` Unstressed right ventricular pressure in mmHg
`RV_Emin` Minimum right ventricular elastance (diastole) in mmHg/ml
`RV_Emax` Maximum right ventricular elastance (systole) in mmHg/ml
`RV_τes` Right ventricular end systolic time in s
`RV_τed` Right ventricular end distolic time in s
`RV_Eshift` Shift time of contraction - 0 for right ventricle
`LA_V₀` Unstressed left atrial volume in ml
`LA_p0` Unstressed left atrial pressure in mmHg
`LA_Emin` Minimum left atrial elastance (diastole) in mmHg/ml
`LA_Emax` Maximum left atrial elastance (systole) in mmHg/ml
`LA_τes` Left atrial end systolic time in s
`LA_τed` Left atrial end distolic time in s
`LA_Eshift` Shift time of contraction in s
`RA_V₀` Unstressed right atrial volume in ml
`RA_p0` Unstressed right atrial pressure in mmHg
`RA_Emin` Minimum right atrial elastance (diastole) in mmHg/ml
`RA_Emax` Maximum right atrial elastance (systole) in mmHg/ml
`RA_τes` Right atrial end systolic time in s
`RA_τed` Right atrial end distolic time in s
`RA_Eshift` Shift time of contraction in s
`AV_CQ` Aortic valve flow coefficent in ml/(s*mmHg^0.5)
`AV_Kp` Pressure effect on the aortic valve in rad/(s^2*mmHg)
`AV_Kf` Frictional effect on the aortic valve in 1/s
`AV_Kb` Fluid velocity effect on the aortic valve in rad/(s*m)
`AV_Kv` Vortex effect on the aortic valve in rad/(s*m)
`AV_θmax` Aortic valve maximum opening angle in rad
`AV_θmin` Aortic valve minimum opening angle in rad
`MV_CQ` Mitral valve flow coefficent in ml/(s*mmHg^0.5)
`MV_Kp` Pressure effect on the mitral valve in rad/(s^2*mmHg)
`MV_Kf` Frictional effect on the mitral valve in 1/s
`MV_Kb` Fluid velocity effect on the mitral valve in rad/(s*m)
`MV_Kv` Vortex effect on the mitral valve in rad/(s*m)
`MV_θmax` Mitral valve maximum opening angle in rad
`MV_θmin` Mitral valve minimum opening angle in rad
`PV_CQ` Pulmonary valve flow coefficent in ml/(s*mmHg^0.5)
`PV_Kp` Pressure effect on the pulmonary valve in rad/(s^2*mmHg)
`PV_Kf` Frictional effect on the pulmonary valve in 1/s
`PV_Kb` Fluid velocity effect on the pulmonary valve in rad/(s*m)
`PV_Kv` Vortex effect on the pulmonary valve in rad/(s*m)
`PV_θmax` Pulmonary valve maximum opening angle in rad
`PV_θmin` Pulmonary valve minimum opening angle in rad
`TV_CQ` Tricuspid valve flow coefficent in ml/(s*mmHg^0.5)
`TV_Kp` Pressure effect on the tricuspid valve in rad/(s^2*mmHg)
`TV_Kf` Frictional effect on the tricuspid valve in 1/s
`TV_Kb` Fluid velocity effect on the tricuspid valve in rad/(s*m)
`TV_Kv` Vortex effect on the pulmonary valve in rad/(s*m)
`TV_θmax` Tricuspid valve maximum opening angle in rad
`TV_θmin` Tricuspid valve minimum opening angle in rad
"""
@mtkmodel ShiHeart begin
@structural_parameters begin
τ
end
@components begin
LHin = Pin()
LHout = Pin()
RHin = Pin()
RHout = Pin()
in = Pin()
out = Pin()
end
@variables begin
Δp(t)
q(t)
end
# sts = []
# ps = @parameters Rc=Rc Rp=Rp C=C
# No parameters in this function
# Parameters are inherited from subcomponents
@components begin
# These are the components the subsystem is made of:
# Ventricles and atria
LV = ShiChamber(V₀, p₀, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
RV = ShiChamber(V₀, p₀, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
LA = ShiChamber(V₀, p₀, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
RA = ShiChamber(V₀, p₀, Eₘᵢₙ, Eₘₐₓ, τ, τₑₛ, τₑₚ, Eshift)
# Valves
AV = ShiValve(CQ, Kp, Kf, Kb, Kv, θmax, θmin)
MV = ShiValve(CQ, Kp, Kf, Kb, Kv, θmax, θmin)
TV = ShiValve(CQ, Kp, Kf, Kb, Kv, θmax, θmin)
PV = ShiValve(CQ, Kp, Kf, Kb, Kv, θmax, θmin)
end
@equations begin
Δp ~ out.p - in.p
q ~ in.q
connect(LHin, LA.in)
connect(LA.out, MV.in)
connect(MV.out, LV.in)
connect(LV.out, AV.in)
connect(AV.out, LHout)
connect(RHin, RA.in)
connect(RA.out, TV.in)
connect(TV.out, RV.in)
connect(RV.out, PV.in)
connect(PV.out, RHout)
end
end
"""
`ResistorDiode(;name, R=1e-3)`
Implements the resistance across a valve following Ohm's law exhibiting diode like behaviour.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Flow in cm^3/s (ml/s)
Named parameters:
`R` Resistance across the valve in mmHg*s/ml
"""
@mtkmodel ResistorDiode begin
@extend OnePort()
@parameters begin
R = 1e-3
end
@equations begin
q ~ -Δp / R * (Δp < 0)
end
end
"""
`OrificeValve(;name, CQ=1.0)`
Implements the square-root pressure-flow relationship across a valve.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Flow in cm^3/s (ml/s)
Named parameters:
`CQ` Flow coefficent in ml/(s*mmHg^0.5)
"""
@mtkmodel OrificeValve begin
@extend OnePort()
@parameters begin
CQ = 1.0
end
@equations begin
q ~ (Δp < 0) * CQ * sqrt(sign(Δp) * Δp)
end
end
"""
`ShiValve(; name, CQ, Kp, Kf, Kb, Kv, θmax, θmin)`
Implements the Shi description for valve opening and closing, full description in [Shi].
Parameters are in the cm, g, s system.
Pressure in mmHg.
Flow in cm^3/s (ml/s)
Maximum and Minimum angles given in rad, to convert from degrees multiply angle by pi/180.
Named parameters:
`CQ` Flow coefficent in ml/(s*mmHg^0.5)
`Kp` Pressure effect on the valve in rad/(s^2*mmHg)
`Kf` Frictional effect on the valve in 1/s
`Kb` Fluid velocity effect on the valve in rad/(s*m)
`Kv` Vortex effect on the valve in rad/(s*m)
`θmax` Valve maximum opening angle in rad
`θmin` Valve minimum opening angle in rad
"""
@component function ShiValve(; name, CQ, Kp, Kf, Kb, Kv, θmax, θmin)
@named oneport = OnePort()
@unpack Δp, q = oneport
ps = @parameters CQ = CQ Kp = Kp Kf = Kf Kb = Kb Kv = Kv θmax = θmax θmin = θmin
sts = @variables θ(t) ω(t) AR(t) Fp(t) Ff(t) Fb(t) Fv(t) F(t)
D = Differential(t)
limits = [
[(θ ~ θmax)] => [ω ~ 0]
[(θ ~ θmin)] => [ω ~ 0]
]
# make θmax the real opening angle and define a θmaxopen for a healthy valve
# that means we can use θmax as a stenosis parameter
θmaxopen = 75 * pi / 180
eqs = [
# Forces/Moments
Fp ~ Kp * -Δp * cos(θ) # pressure
Ff ~ -Kf * ω # friction
Fb ~ Kb * q * cos(θ) # Fluid Velocity
Fv ~ -Kv * q * (q > 0) * sin(2θ) # vortex behind leaflets
F ~ Fp + Ff + Fb + Fv # total force/moment on leaflets
#ODEs
D(θ) ~ ω
D(ω) ~ F * ((θ < θmax) * (F > 0) + (θ > θmin) * (F < 0))
# Opening ratio
#AR ~ ((1 - cos(θ))^2) / ((1 - cos(θmax))^2)
AR ~ ((1 - cos(θ))^2) / ((1 - cos(θmaxopen))^2)
# Flow equation
q ~ -sign(Δp) * CQ * AR * sqrt(abs(Δp))
]
# include the `continuous_events` definition `limits` in the ODE system
# this is the MTK equivalent to callbacks
extend(ODESystem(eqs, t, sts, ps; name=name, continuous_events=limits), oneport)
end
"""
`MynardValve_SemiLunar(; name, ρ, Leff, Mrg, Mst, Ann, Kvc, Kvo)`
Implements the Mynard description for flow across the semilunar valves, full description in [Mynard].
This valve description corresponds to the semilunar valves where interia is an effect we consider.
Note: The minimum level of regurgitation has to be set to machine precision eps()
Parameters are in the cm, g, s system.
Pressure in mmHg.
Flow in cm^3/s (ml/s)
p is scaled to ensure units are consistent throughout.
Named parameters:
name name of the element
`ρ` Blood density in g/cm^3
`Leff` An effective length in cm
`Mrg` Level of regurgitation exhibited by a valve in DN
`Mst` Level of stenosis exhibited by a valve in DN
`Ann` Annulus area in cm^2
`Kvc` Valve closing rate coefficent in cm^2/(dynes*s)
`Kvo` Valve opening rate coefficent in cm^2/(dynes*s)
p is calculated in mmHg
q is calculated in cm^3/s (ml/s)
"""
@mtkmodel MynardValve_SemiLunar begin
@extend OnePort()
@parameters begin
ρ
Leff
Mrg
Mst
Ann
Kvc
Kvo
end
@variables begin
Aeff(t)
ζ(t)
B(t)
Aeff_min(t)
Aeff_max(t)
L(t)
end
begin
Δp = -1333.22 * Δp
end
@equations begin
# Opening ratio
D(ζ) ~ (Δp > 0) * ((1 - ζ) * Kvo * Δp) + (Δp < 0) * (ζ * Kvc * Δp)
Aeff_min ~ Mrg * Ann + eps()
Aeff_max ~ Mst * Ann
Aeff ~ (Aeff_max - Aeff_min) * ζ + Aeff_min
# Flow equation
B ~ ρ / (2 * Aeff^2)
L ~ ρ * Leff / Aeff
D(q) ~ (Δp - B * q * abs(q)) * 1 / L
end
end
"""
`MynardValve_Atrioventricular(; name, ρ, Mrg, Mst, Ann, Kvc, Kvo)`
Implements the Mynard description for flow across the atrioventricular valves, full description in [Mynard].
This valve description corresponds to the atrioventricular valves where interia is not considered.
Note: The minimum level of regurgitation has to be set to machine precision eps()
Parameters are in the cm, g, s system.
Pressure in mmHg.
Flow in cm^3/s (ml/s)
p is scaled to ensure units are consistent throughout.
Named parameters:
name name of the element
`ρ` Blood density in g/cm^3
`Mrg` Level of regurgitation exhibited by a valve in DN
`Mst` Level of stenosis exhibited by a valve in DN
`Ann` Annulus area in cm^2
`Kvc` Valve closing rate coefficent in cm^2/(dynes*s)
`Kvo` Valve opening rate coefficent in cm^2/(dynes*s)
p is calculated in mmHg
q is calculated in cm^3/s (ml/s)
"""
@mtkmodel MynardValve_Atrioventricular begin
@extend OnePort()
@parameters begin
ρ
Mrg
Mst
Ann
Kvc
Kvo
end
@variables begin
Aeff(t)
ζ(t)
B(t)
Aeff_min(t)
Aeff_max(t)
L(t)
end
begin
p = -1333.22 * p
end
@equations begin
# Opening ratio
D(ζ) ~ (Δp > 0) * ((1 - ζ) * Kvo * Δp) + (Δp < 0) * (ζ * Kvc * Δp)
Aeff_min ~ Mrg * Ann + eps()
Aeff_max ~ Mst * Ann
Aeff ~ (Aeff_max - Aeff_min) * ζ + Aeff_min
# Flow equation
B ~ ρ / (2 * Aeff^2)
q ~ sqrt(1 / B * abs(Δp)) * sign(Δp)
end
end
"""
`WK3(;name, Rc=1.0, Rp=1.0, C=1.0)`
Implements the 3 element windkessel model.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s)
Named parameters:
`Rc`: Characteristic impedance in mmHg*s/ml
`Rp`: Peripheral resistance in mmHg*s/ml
`C`: Arterial compliance in ml/mmHg
"""
@mtkmodel WK3 begin
@extend OnePort()
@components begin
Rc = Resistor(R=1.0)
Rp = Resistor(R=1.0)
C = Capacitor(C=1.0)
ground = Ground()
end
@equations begin
connect(in, Rc.in)
connect(Rc.out, Rp.in, C.in)
connect(Rp.out, C.out, out)
end
end
"""
`WK3E(;name, Rc=1.0, Rp=1.0, E=1.0)`
Implements the 3 element windkessel model. With a vessel elastance instead of a capacitor.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s)
Named parameters:
`Rc`: Characteristic impedance in mmHg*s/ml
`Rp`: Peripheral resistance in mmHg*s/ml
`E`: Arterial elastance in mmHg/ml
"""
@mtkmodel WK3E begin
@extend OnePort()
@components begin
Rc = Resistor(R=1.0)
Rp = Resistor(R=1.0)
E = Elastance(E=1.0)
ground = Ground()
end
@equations begin
connect(in, Rc.in)
connect(Rc.out, E.in)
connect(E.out, Rp.in)
connect(Rp.out, out)
end
end
"""
`WK4_S(;name, Rc=1.0, L=1.0, Rp=1.0, C=1.0)`
Implements the 4 element windkessel model with serial inertance.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s)
Named parameters:
`Rc`: Characteristic impedance in mmHg*s/ml
`L`: Inertance/Inductance in mmHg*s^2*ml^-1
`Rp`: Peripheral resistance in mmHg*s/ml
`C`: Arterial compliance in ml/mmHg
"""
@mtkmodel WK4_S begin
@extend OnePort()
@components begin
# These are the components the subsystem is made of:
Rc = Resistor(R)
Rp = Resistor(R)
C = Capacitor(C)
L = Inductance(L)
ground = Ground()
end
# The equations for the subsystem are created by
# 'connect'-ing the components
@equations begin
connect(in, Rc.in)
connect(Rc.out, L.in)
connect(L.out, C.in, Rp.in)
connect(Rp.out, C.out, out)
end
end
"""
`WK4_SE(;name, Rc=1.0, L=1.0, Rp=1.0, E=1.0)`
Implements the 4 element windkessel model with serial inertance.
With a vessel elastance instead of a capacitor.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s)
Named parameters:
`Rc`: Characteristic impedance in mmHg*s/ml
`L`: Inertance/Inductance in mmHg*s^2*ml^-1
`Rp`: Peripheral resistance in mmHg*s/ml
`E`: Arterial elastance in mmHg/ml
"""
@mtkmodel WK4_SE begin
@extend OnePort()
@components begin
# These are the components the subsystem is made of:
Rc = Resistor(R)
Rp = Resistor(R)
E = Elastance(E)
L = Inductance(L)
ground = Ground()
end
# The equations for the subsystem are created by
# 'connect'-ing the components
@equations begin
connect(in, Rc.in)
connect(Rc.out, L.in)
connect(L.out, E.in)
connect(E.out, Rp.in)
connect(Rp.out, out)
end
end
"""
`WK4_P(;name, Rc=1.0, L=1.0, Rp=1.0, C=1.0)`
Implements the 4 element windkessel model with parallel inertance.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s)
Named parameters:
`Rc`: Characteristic impedance in mmHg*s/ml
`L`: Inertance/Inductance in mmHg*s^2*ml^-1
`Rp`: Peripheral resistance in mmHg*s/ml
`C`: Arterial compliance in ml/mmHg
"""
@mtkmodel WK4_P begin
@extend OnePort()
@components begin
Rc = Resistor(R=1.0)
Rp = Resistor(R=1.0)
C = Capacitor(C=1.0)
L = Inductance(L=1.0)
ground = Ground()
end
# The equations for the subsystem are created by
# 'connect'-ing the components
@equations begin
connect(in, L.in, Rc.in)
connect(L.out, Rc.out, C.in, Rp.in)
connect(Rp.out, C.out, out)
end
end
"""
`WK4_PE(;name, Rc=1.0, L=1.0, Rp=1.0, E=1.0)`
Implements the 4 element windkessel model with parallel inertance.
With a vessel elastance instead of a capacitor.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s)
Named parameters:
`Rc`: Characteristic impedance in mmHg*s/ml
`L`: Inertance/Inductance in mmHg*s^2*ml^-1
`Rp`: Peripheral resistance in mmHg*s/ml
`E`: Arterial elastance in mmHg/ml
"""
@mtkmodel WK4_PE begin
@extend OnePort()
@components begin
Rc = Resistor(R=1.0)
Rp = Resistor(R=1.0)
E = Elastance(E=1.0)
L = Inductance(L=1.0)
ground = Ground()
end
@equations begin
connect(in, L.in, Rc.in)
connect(L.out, Rc.out, E.in)
connect(E.out, Rp.in)
connect(Rp.out, out)
end
end
@mtkmodel WK5 begin
@extend OnePort()
@components begin
R1 = Resistor(R=1.0)
C1 = Capacitor(C=1.0)
R2 = Resistor(R=1.0)
C2 = Capacitor(C=1.0)
R3 = Resistor(R=1.0)
L = Inductance(L=1.0)
ground = Ground()
end
@equations begin
connect(in, R1.in)
connect(R1.out, C1.in, R2.in)
connect(R2.out, C2.in, R3.in)
connect(R3.out, C1.out, C2.out, out)
end
end
@mtkmodel WK5E begin
@extend OnePort()
@components begin
R1 = Resistor(R=1.0)
E1 = Elastance(E=1.0)
R2 = Resistor(R=1.0)
E2 = Elastance(E=1.0)
R3 = Resistor(R=1.0)
L = Inductance(L=1.0)
ground = Ground()
end
@equations begin
connect(in, R1.in)
connect(R1.out, E1.in)
connect(E1.out, R2.in)
connect(R2.out, E2.in)
connect(E2.out, R3.in)
connect(R3.out, out)
end
end
"""
`CR(;name, R=1.0, C=1.0)`
Implements the compliance, resistor subsystem.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s).
Named parameters:
`R`: Component resistance in mmHg*s/ml
`C`: Component compliance in ml/mmHg
"""
@mtkmodel CR begin
@structural_parameters begin
R=1.0
C=1.0
end
@variables begin
Δp(t)
q(t)
end
@components begin
in = Pin()
out = Pin()
R = Resistor(R=R)
C = Compliance(C=C)
end
@equations begin
Δp ~ out.p - in.p
q ~ in.q
connect(in, C.in)
connect(C.out, R.in)
connect(R.out, out)
end
end
"""
`CRL(;name, C=1.0, R=1.0, L=1.0)`
Implements the compliance, resistor, inductance subsystem.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s).
Named parameters:
`C`: Component compliance in ml/mmHg
`R`: Component resistance in mmHg*s/ml
`L`: Component blood inertia in mmHg*s^2/ml
"""
@mtkmodel CRL begin
@structural_parameters begin
C=1.0
R=1.0
L=1.0
end
@variables begin
Δp(t)
q(t)
end
@components begin
in = Pin()
out = Pin()
C = Compliance(C=C)
R = Resistor(R=R)
L = Inductance(L=L)
end
@equations begin
Δp ~ out.p - in.p
q ~ in.q
connect(in, C.in)
connect(C.out, R.in)
connect(R.out, L.in)
connect(L.out, out)
end
end
"""
`RRCR(;name, R1=1.0, R2=1.0, R3=1.0, C=1.0)`
Implements the resistor, resistor, compliance, resistor subsystem.
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s).
Named parameters:
`R1`: Component resistance in mmHg*s/ml
`R2`: Component resistance in mmHg*s/ml
`C`: Component compliance in ml/mmHg
`R3`: Component resistance in mmHg*s/ml
"""
@mtkmodel RRCR begin
@variables begin
p(t)
q(t)
end
@components begin
in = Pin()
out = Pin()
ep = Pin()
R1 = Resistor(R)
R2 = Resistor(R)
C = Compliance_ep(C)
R3 = Resistor(R)
end
@equations begin
p ~ out.p - in.p
q ~ in.q
connect(in, R1.in)
connect(R1.out, R2.in)
connect(R2.out, C.in)
connect(C.out, R3.in)
connect(R3.out, out)
connect(C.ep, ep)
end
end
"""
`ShiSystemicLoop(; name, SAS.C, SAS.R, SAS.L, SAT.C, SAT.R, SAT.L, SAR.R, SCP.R, SVN.C, SVN.R)`
Implements systemic loop as written by Shi in [Shi].
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s).
Named parameters:
`SAS_C`: Aortic sinus compliance in ml/mmHg
`SAS_R`: Aortic sinus resistance in mmHg*s/ml
`SAS_L`: Aortic sinus inductance in mmHg*s^2/ml
`SAT_C`: Artery compliance in ml/mmHg
`SAT_R`: Artery resistance in mmHg*s/ml
`SAT_L`: Artery inductance in mmHg*s^2/ml
`SAR_R`: Arteriole resistance in mmHg*s/ml
`SCP_R`: Capillary resistance in mmHg*s/ml
`SVN_C`: Vein compliance in ml/mmHg
`SVN_R`: Vein resistance in mmHg*s/ml
"""
@mtkmodel ShiSystemicLoop begin
@variables begin
Δp(t)
q(t)
end
@components begin
in = Pin()
out = Pin()
# These are the components the subsystem is made of:
## Systemic Aortic Sinus ##
SAS = CRL(C, R, L)
## Systemic Artery ##
SAT = CRL(C, R, L)
## Systemic Arteriole ##
SAR = Resistor(R)
## Systemic Capillary ##
SCP = Resistor(R)
## Systemic Vein ##
SVN = CR(C, R)
end
@equations begin
Δp ~ out.p - in.p
q ~ in.q
connect(in, SAS.in)
connect(SAS.out, SAT.in)
connect(SAT.out, SAR.in)
connect(SAR.out, SCP.in)
connect(SCP.out, SVN.in)
connect(SVN.out, out)
end
end
"""
`ShiPulmonaryLoop(; name, PAS.C, PAS.R, PAS.L, PAT.C, PAT.R, PAT.L, PAR.R, PCP.R, PVN.C, PVN.R)`
Implements systemic loop as written by Shi in [Shi].
Parameters are in the cm, g, s system.
Pressure in mmHg.
Volume in ml.
Flow in cm^3/s (ml/s).
Named parameters:
`PAS__C`: Artery sinus compliance in ml/mmHg
`PAS__R`: Artery sinus resistance in mmHg*s/ml
`PAS__L`: Artery sinus Inductance in mmHg*s^2/ml
`PAT__C`: Artery compliance in ml/mmHg
`PAT__R`: Artery resistance in mmHg*s/ml
`PAT__L`: Artery Inductance in mmHg*s^2/ml
`PAR__R`: Arteriole resistance in mmHg*s/ml
`PCP__R`: Capillary resistance in mmHg*s/ml
`PVN__C`: Vein compliance in ml/mmHg
`PVN__R`: Vein resistance in mmHg*s/ml
"""
@mtkmodel ShiPulmonaryLoop begin
@variables begin
Δp(t)
q(t)
end
@components begin
in = Pin()
out = Pin()
# These are the components the subsystem is made of:
## Pulmonary Aortic Sinus ##
PAS = CRL(C, R, L)
## Pulmonary Artery ##
PAT = CRL(C, R, L)
## Pulmonary Arteriole ##
PAR = Resistor(R)
## Pulmonary Capillary ##
PCP = Resistor(R)
## Pulmonary Vein ##
PVN = CR(C, R)
end
@equations begin
Δp ~ out.p - in.p
q ~ in.q
connect(in, PAS.in)
connect(PAS.out, PAT.in)
connect(PAT.out, PAR.in)
connect(PAR.out, PCP.in)
connect(PCP.out, PVN.in)
connect(PVN.out, out)
end
end
end
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | code | 2639 | τ = 1.0
Eshift=0.0
Ev=Inf
#### LV chamber parameters #### Checked
v0_lv = 5.0
p0_lv = 1.0
Emin_lv = 0.1
Emax_lv = 2.5
τes_lv = 0.3
τed_lv = 0.45
Eshift_lv = 0.0
#### RV Chamber parameters #### Checked
v0_rv = 10.0
p0_rv = 1.0
Emin_rv = 0.1
Emax_rv = 1.15
τes_rv = 0.3
τed_rv = 0.45
Eshift_rv = 0.0
### LA Atrium Parameters #### Checked
v0_la = 4.0
p0_la = 1.0
Emin_la = 0.15
Emax_la = 0.25
τpwb_la = 0.92
τpww_la = 0.09
τes_la = τpww_la/2
τed_la = τpww_la
Eshift_la = τpwb_la
### RA Atrium parameters #### Checked
v0_ra = 4.0
p0_ra = 1.0
Emin_ra = 0.15
Emax_ra = 0.25
τpwb_ra = 0.92
τpww_ra = 0.09
τes_ra = τpww_ra/2
τed_ra = τpww_ra
Eshift_ra = τpwb_ra
#### Valve parameters #### Checked
CQ_AV = 350.0
CQ_MV = 400.0
CQ_TV = 400.0
CQ_PV = 350.0
## Systemic Aortic Sinus #### Checked
Csas = 0.08
Rsas = 0.003
Lsas = 6.2e-5
pt0sas = 100.0
qt0sas = 0.0
## Systemic Artery #### Checked
Csat = 1.6
Rsat = 0.05
Lsat = 0.0017
pt0sat = 100.0
qt0sat = 0.0
## Systemic Arteriole #### Checked
Rsar = 0.5
## Systemic Capillary #### Checked
Rscp = 0.52
## Systemic Vein #### Checked
Csvn = 20.5
Rsvn = 0.075
pt0svn = 0.0
qt0svn = 0.0
## Pulmonary Aortic Sinus #### Checked
Cpas = 0.18
Rpas = 0.002
Lpas = 5.2e-5
pt0pas = 30.0
qt0pas = 0.0
## Pulmonary Artery #### Checked
Cpat = 3.8
Rpat = 0.01
Lpat = 0.0017
pt0pat = 30.0
qt0pat = 0.0
## Pulmonary Arteriole #### Checked
Rpar = 0.05
## Pulmonary Capillary #### Checked
Rpcp = 0.25
## Pulmonary Vein #### Checked
Cpvn = 20.5
Rpvn = 0.006 # this was 0.006 originally and in the paper, seems to be wrong in the paper!
# CHANGED THIS IN THE CELLML MODEL AS WELL TO MATCH THE PAPER!!!!!
pt0pvn = 0.0
qt0pvn = 0.0
## KG diaphragm ## Not in cellML model
# left heart #
Kst_la = 2.5
Kst_lv = 20.0
Kf_sav = 0.0004
Ke_sav = 9000.0
M_sav = 0.0004
A_sav = 0.00047
# right heart #
Kst_ra = 2.5
Kst_rv = 20.0
Kf_pav = 0.0004
Ke_pav = 9000.0
M_pav = 0.0004
A_pav = 0.00047
#
#### Diff valve params #### not in cellML model
Kp_av = 5500.0 # * 57.29578 # Shi Paper has values in radians!
Kf_av = 50.0
Kf_mv = 50.0
Kp_mv = 5500.0 # * 57.29578
Kf_tv = 50.0
Kp_tv = 5500.0 # * 57.29578
Kf_pv = 50.0
Kp_pv = 5500.0 #* 57.29578
Kb_av = 2.0
Kv_av = 7.0
Kb_mv = 2.0
Kv_mv = 3.5
Kb_tv = 2.0
Kv_tv = 3.5
Kb_pv = 2.0
Kv_pv = 3.5
θmax_av = 75.0 * pi / 180
θmax_mv = 75.0 * pi / 180
θmin_av = 5.0 * pi / 180
θmin_mv = 5.0 * pi / 180
θmax_pv = 75.0 * pi / 180
θmax_tv = 75.0 * pi / 180
θmin_pv = 5.0 * pi / 180
θmin_tv = 5.0 * pi / 180
## pressure force and frictional force is the same for all 4 valves
# Initial conditions #### Checked against cellML model
LV_Vt0 = 500
RV_Vt0 = 500
LA_Vt0 = 20
RA_Vt0 = 20
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | code | 21112 | ##
using CirculatorySystemModels
using ModelingToolkit
using OrdinaryDiffEq
using Test
using CSV
using DataFrames
##
# @testset "WK5" begin
# end
@testset "Shi Model in V" begin
##
include("ShiParam.jl")
@independent_variables t
## Ventricles
@named LV = ShiChamber(V₀=v0_lv, p₀=p0_lv, Eₘᵢₙ=Emin_lv, Eₘₐₓ=Emax_lv, τ=τ, τₑₛ=τes_lv, τₑₚ=τed_lv, Eshift=0.0)
# The atrium can be defined either as a ShiChamber with changed timing parameters, or as defined in the paper
@named LA = ShiChamber(V₀=v0_la, p₀=p0_la, Eₘᵢₙ=Emin_la, Eₘₐₓ=Emax_la, τ=τ, τₑₛ=τpww_la / 2, τₑₚ=τpww_la, Eshift=τpwb_la)
@named RV = ShiChamber(V₀=v0_rv, p₀=p0_rv, Eₘᵢₙ=Emin_rv, Eₘₐₓ=Emax_rv, τ=τ, τₑₛ=τes_rv, τₑₚ=τed_rv, Eshift=0.0)
# The atrium can be defined either as a ShiChamber with changed timing parameters, or as defined in the paper
# @named RA = ShiChamber(V₀=v0_ra, p₀ = p0_ra, Eₘᵢₙ=Emin_ra, Eₘₐₓ=Emax_ra, τ=τ, τₑₛ=τpww_ra/2, τₑₚ =τpww_ra, Eshift=τpwb_ra)
@named RA = ShiAtrium(V₀=v0_ra, p₀=1, Eₘᵢₙ=Emin_ra, Eₘₐₓ=Emax_ra, τ=τ, τpwb=τpwb_ra, τpww=τpww_ra) #, Ev=Inf)
## Valves as simple valves
@named AV = OrificeValve(CQ=CQ_AV)
@named MV = OrificeValve(CQ=CQ_MV)
@named TV = OrificeValve(CQ=CQ_TV)
@named PV = OrificeValve(CQ=CQ_PV)
####### Systemic Loop #######
# Systemic Aortic Sinus ##
@named SAS = CRL(C=Csas, R=Rsas, L=Lsas)
# Systemic Artery ##
@named SAT = CRL(C=Csat, R=Rsat, L=Lsat)
# Systemic Arteriole ##
@named SAR = Resistor(R=Rsar)
# Systemic Capillary ##
@named SCP = Resistor(R=Rscp)
# Systemic Vein ##
@named SVN = CR(R=Rsvn, C=Csvn)
####### Pulmonary Loop #######
# Pulmonary Aortic Sinus ##
@named PAS = CRL(C=Cpas, R=Rpas, L=Lpas)
# Pulmonary Artery ##
@named PAT = CRL(C=Cpat, R=Rpat, L=Lpat)
# Pulmonary Arteriole ##
@named PAR = Resistor(R=Rpar)
# Pulmonary Capillary ##
@named PCP = Resistor(R=Rpcp)
# Pulmonary Vein ##
@named PVN = CR(R=Rpvn, C=Cpvn)
##
circ_eqs = [
connect(LV.out, AV.in)
connect(AV.out, SAS.in)
connect(SAS.out, SAT.in)
connect(SAT.out, SAR.in)
connect(SAR.out, SCP.in)
connect(SCP.out, SVN.in)
connect(SVN.out, RA.in)
connect(RA.out, TV.in)
connect(TV.out, RV.in)
connect(RV.out, PV.in)
connect(PV.out, PAS.in)
connect(PAS.out, PAT.in)
connect(PAT.out, PAR.in)
connect(PAR.out, PCP.in)
connect(PCP.out, PVN.in)
connect(PVN.out, LA.in)
connect(LA.out, MV.in)
connect(MV.out, LV.in)
]
## Compose the whole ODE system
@named _circ_model = ODESystem(circ_eqs, t)
@named circ_model = compose(_circ_model,
[LV, RV, LA, RA, AV, MV, PV, TV, SAS, SAT, SAR, SCP, SVN, PAS, PAT, PAR, PCP, PVN])
## And simplify it
circ_sys = structural_simplify(circ_model)
## Setup ODE
# Initial Conditions for Shi Valve
# u0 = [LV_Vt0, RV_Vt0, LA_Vt0, RA_Vt0, pt0sas, qt0sas , pt0sat, qt0sat, pt0svn, pt0pas, qt0pas, pt0pat, qt0pat, pt0pvn, 0, 0, 0, 0,0, 0, 0, 0]
# and for OrificeValve --- Commment this next line to use ShiValves
# u0 = [LV_Vt0, RV_Vt0, LA_Vt0, RA_Vt0, pt0sas, qt0sas, pt0sat, qt0sat, pt0svn, pt0pas, qt0pas, pt0pat, qt0pat, pt0pvn]
u0 = [
LV.V => LV_Vt0
RV.V => RV_Vt0
LA.V => LA_Vt0
RA.V => RA_Vt0
SAS.C.p => pt0sas
SAS.L.q => qt0sas
SAT.C.p => pt0sat
SAT.L.q => qt0sat
SVN.C.p => pt0svn
PAS.C.p => pt0pas
PAS.L.q => qt0pas
PAT.C.p => pt0pat
PAT.L.q => qt0pat
PVN.C.p => pt0pvn
]
prob = ODEProblem(circ_sys, u0, (0.0, 20.0))
##
@time ShiSimpleSolV = solve(prob, Tsit5(), reltol=1e-9, abstol=1e-12, saveat=19:0.01:20)
# ShiSimpleSolV = ShiSimpleSolV(19:0.01:20)
## Read benchmark data and compare
ShiBench = CSV.read("ShiSimple.csv", DataFrame)
@test SciMLBase.successful_retcode(ShiSimpleSolV)
@test sum((ShiSimpleSolV[LV.V] .- ShiBench[!, :LV_V]) ./ ShiBench[!, :LV_V]) / length(ShiSimpleSolV.u) ≈ 0 atol = 1e-3
@test sum((ShiSimpleSolV[RV.V] .- ShiBench[!, :RV_V]) ./ ShiBench[!, :RV_V]) / length(ShiSimpleSolV.u) ≈ 0 atol = 1e-3
@test sum((ShiSimpleSolV[LA.V] .- ShiBench[!, :LA_V]) ./ ShiBench[!, :LA_V]) / length(ShiSimpleSolV.u) ≈ 0 atol = 1e-3
@test sum((ShiSimpleSolV[RA.V] .- ShiBench[!, :RA_V]) ./ ShiBench[!, :RA_V]) / length(ShiSimpleSolV.u) ≈ 0 atol = 1e-3
end
##
@testset "Shi Model in P" begin
include("ShiParam.jl")
## Start Modelling
@independent_variables t
## Ventricles
@named LV = ShiChamber(V₀=v0_lv, p₀=p0_lv, Eₘᵢₙ=Emin_lv, Eₘₐₓ=Emax_lv, τ=τ, τₑₛ=τes_lv, τₑₚ=τed_lv, Eshift=0.0, inP=true)
# The atrium can be defined either as a ShiChamber with changed timing parameters, or as defined in the paper
@named LA = ShiChamber(V₀=v0_la, p₀=p0_la, Eₘᵢₙ=Emin_la, Eₘₐₓ=Emax_la, τ=τ, τₑₛ=τpww_la / 2, τₑₚ=τpww_la, Eshift=τpwb_la, inP=true)
@named RV = ShiChamber(V₀=v0_rv, p₀=p0_rv, Eₘᵢₙ=Emin_rv, Eₘₐₓ=Emax_rv, τ=τ, τₑₛ=τes_rv, τₑₚ=τed_rv, Eshift=0.0, inP=true)
# The atrium can be defined either as a ShiChamber with changed timing parameters, or as defined in the paper
# @named RA = ShiChamber(V₀=v0_ra, p₀ = p0_ra, Eₘᵢₙ=Emin_ra, Eₘₐₓ=Emax_ra, τ=τ, τₑₛ=τpww_ra/2, τₑₚ =τpww_ra, Eshift=τpwb_ra)
@named RA = ShiAtrium(V₀=v0_ra, p₀=1, Eₘᵢₙ=Emin_ra, Eₘₐₓ=Emax_ra, τ=τ, τpwb=τpwb_ra, τpww=τpww_ra, inP=true) #, Ev=Inf)
## Valves as simple valves
@named AV = OrificeValve(CQ=CQ_AV)
@named MV = OrificeValve(CQ=CQ_MV)
@named TV = OrificeValve(CQ=CQ_TV)
@named PV = OrificeValve(CQ=CQ_PV)
####### Systemic Loop #######
# Systemic Aortic Sinus ##
@named SAS = CRL(C=Csas, R=Rsas, L=Lsas)
# Systemic Artery ##
@named SAT = CRL(C=Csat, R=Rsat, L=Lsat)
# Systemic Arteriole ##
@named SAR = Resistor(R=Rsar)
# Systemic Capillary ##
@named SCP = Resistor(R=Rscp)
# Systemic Vein ##
@named SVN = CR(R=Rsvn, C=Csvn)
####### Pulmonary Loop #######
# Pulmonary Aortic Sinus ##
@named PAS = CRL(C=Cpas, R=Rpas, L=Lpas)
# Pulmonary Artery ##
@named PAT = CRL(C=Cpat, R=Rpat, L=Lpat)
# Pulmonary Arteriole ##
@named PAR = Resistor(R=Rpar)
# Pulmonary Capillary ##
@named PCP = Resistor(R=Rpcp)
# Pulmonary Vein ##
@named PVN = CR(R=Rpvn, C=Cpvn)
##
circ_eqs = [
connect(LV.out, AV.in)
connect(AV.out, SAS.in)
connect(SAS.out, SAT.in)
connect(SAT.out, SAR.in)
connect(SAR.out, SCP.in)
connect(SCP.out, SVN.in)
connect(SVN.out, RA.in)
connect(RA.out, TV.in)
connect(TV.out, RV.in)
connect(RV.out, PV.in)
connect(PV.out, PAS.in)
connect(PAS.out, PAT.in)
connect(PAT.out, PAR.in)
connect(PAR.out, PCP.in)
connect(PCP.out, PVN.in)
connect(PVN.out, LA.in)
connect(LA.out, MV.in)
connect(MV.out, LV.in)
]
## Compose the whole ODE system
@named _circ_model = ODESystem(circ_eqs, t)
@named circ_model = compose(_circ_model,
[LV, RV, LA, RA, AV, MV, PV, TV, SAS, SAT, SAR, SCP, SVN, PAS, PAT, PAR, PCP, PVN])
## And simplify it
circ_sys = structural_simplify(circ_model)
## Setup ODE
# Initial Conditions for Shi Valve
# u0 = [LV_Vt0, RV_Vt0, LA_Vt0, RA_Vt0, pt0sas, qt0sas , pt0sat, qt0sat, pt0svn, pt0pas, qt0pas, pt0pat, qt0pat, pt0pvn, 0, 0, 0, 0,0, 0, 0, 0]
# and for OrificeValve --- Commment this next line to use ShiValves
# u0 = [LV_Vt0, RV_Vt0, LA_Vt0, RA_Vt0, pt0sas, qt0sas, pt0sat, qt0sat, pt0svn, pt0pas, qt0pas, pt0pat, qt0pat, pt0pvn]
u0 = [
LV.V => LV_Vt0
RV.V => RV_Vt0
LA.V => LA_Vt0
RA.V => RA_Vt0
SAS.C.p => pt0sas
SAS.L.q => qt0sas
SAT.C.p => pt0sat
SAT.L.q => qt0sat
SVN.C.p => pt0svn
PAS.C.p => pt0pas
PAS.L.q => qt0pas
PAT.C.p => pt0pat
PAT.L.q => qt0pat
PVN.C.p => pt0pvn
]
prob = ODEProblem(circ_sys, u0, (0.0, 20.0))
##
@time ShiSimpleSolP = solve(prob, Tsit5(), reltol=1e-9, abstol=1e-12, saveat=19:0.01:20)
# ShiSimpleSolP = ShiSimpleSolP(19:0.01:20)
## Read benchmark data and compare
ShiBench = CSV.read("ShiSimple.csv", DataFrame)
@test SciMLBase.successful_retcode(ShiSimpleSolP)
@test sum((ShiSimpleSolP[LV.V] .- ShiBench[!, :LV_V]) ./ ShiBench[!, :LV_V]) / length(ShiSimpleSolP.u) ≈ 0 atol = 2e-3
@test sum((ShiSimpleSolP[RV.V] .- ShiBench[!, :RV_V]) ./ ShiBench[!, :RV_V]) / length(ShiSimpleSolP.u) ≈ 0 atol = 2e-3
@test sum((ShiSimpleSolP[LA.V] .- ShiBench[!, :LA_V]) ./ ShiBench[!, :LA_V]) / length(ShiSimpleSolP.u) ≈ 0 atol = 2e-3
@test sum((ShiSimpleSolP[RA.V] .- ShiBench[!, :RA_V]) ./ ShiBench[!, :RA_V]) / length(ShiSimpleSolP.u) ≈ 0 atol = 2e-3
end
##
@testset "Shi Model Complex" begin
include("ShiParam.jl")
## Start Modelling
@independent_variables t
## Shi Heart (with AV stenosis: max AV opening angle = 40 degrees!)
@mtkmodel CirculatoryModel begin
@components begin
heart = ShiHeart(τ=τ,
LV.V₀=v0_lv, LV.p₀=p0_lv, LV.Eₘᵢₙ=Emin_lv, LV.Eₘₐₓ=Emax_lv, LV.τ=τ, LV.τₑₛ=τes_lv, LV.τₑₚ=τed_lv, LV.Eshift=0.0,
RV.V₀=v0_rv, RV.p₀=p0_rv, RV.Eₘᵢₙ=Emin_rv, RV.Eₘₐₓ=Emax_rv, RV.τ=τ, RV.τₑₛ=τes_rv, RV.τₑₚ=τed_rv, RV.Eshift=0.0,
LA.V₀=v0_la, LA.p₀=p0_la, LA.Eₘᵢₙ=Emin_la, LA.Eₘₐₓ=Emax_la, LA.τ=τ, LA.τₑₛ=τpww_la / 2, LA.τₑₚ=τpww_la, LA.Eshift=τpwb_la,
RA.V₀=v0_ra, RA.p₀=p0_ra, RA.Eₘᵢₙ=Emin_ra, RA.Eₘₐₓ=Emax_ra, RA.τ=τ, RA.τₑₛ=τpww_ra / 2, RA.τₑₚ=τpww_ra, RA.Eshift=τpwb_ra,
AV.CQ=CQ_AV, AV.Kp=Kp_av, AV.Kf=Kf_av, AV.Kb=0.0, AV.Kv=3.5, AV.θmax=40.0 * pi / 180, AV.θmin=5.0 * pi / 180,
MV.CQ=CQ_MV, MV.Kp=Kp_mv, MV.Kf=Kf_mv, MV.Kb=0.0, MV.Kv=3.5, MV.θmax=75.0 * pi / 180, MV.θmin=5.0 * pi / 180,
TV.CQ=CQ_TV, TV.Kp=Kp_tv, TV.Kf=Kf_tv, TV.Kb=0.0, TV.Kv=3.5, TV.θmax=75.0 * pi / 180, TV.θmin=5.0 * pi / 180,
PV.CQ=CQ_PV, PV.Kp=Kp_pv, PV.Kf=Kf_pv, PV.Kb=0.0, PV.Kv=3.5, PV.θmax=75.0 * pi / 180, PV.θmin=5.0 * pi / 180
)
syst_loop = ShiSystemicLoop(SAS.C=Csas, SAS.R=Rsas, SAS.L=Lsas,
SAT.C=Csat, SAT.R=Rsat, SAT.L=Lsat,
SAR.R=Rsar, SCP.R=Rscp, SVN.C=Csvn, SVN.R=Rsvn
)
pulm_loop = ShiPulmonaryLoop(PAS.C=Cpas, PAS.R=Rpas, PAS.L=Lpas,
PAT.C=Cpat, PAT.R=Rpat, PAT.L=Lpat,
PAR.R=Rpar, PCP.R=Rpcp, PVN.C=Cpvn, PVN.R=Rpvn
)
end
@equations begin
connect(heart.LHout, syst_loop.in)
connect(syst_loop.out, heart.RHin)
connect(heart.RHout, pulm_loop.in)
connect(pulm_loop.out, heart.LHin)
end
end
@mtkbuild circ_sys = CirculatoryModel()
u0 = [
circ_sys.heart.LV.V => LV_Vt0
circ_sys.heart.RV.V => RV_Vt0
circ_sys.heart.LA.V => LA_Vt0
circ_sys.heart.RA.V => RA_Vt0
circ_sys.heart.AV.θ => 0
circ_sys.heart.AV.ω => 0
circ_sys.heart.MV.θ => 0
circ_sys.heart.MV.ω => 0
circ_sys.heart.TV.θ => 0
circ_sys.heart.TV.ω => 0
circ_sys.heart.PV.θ => 0
circ_sys.heart.PV.ω => 0
circ_sys.syst_loop.SAS.C.p => pt0sas
circ_sys.syst_loop.SAS.L.q => qt0sas
circ_sys.syst_loop.SAT.C.p => pt0sat
circ_sys.syst_loop.SAT.L.q => qt0sat
circ_sys.syst_loop.SVN.C.p => pt0svn
circ_sys.pulm_loop.PAS.C.p => pt0pas
circ_sys.pulm_loop.PAS.L.q => qt0pas
circ_sys.pulm_loop.PAT.C.p => pt0pat
circ_sys.pulm_loop.PAT.L.q => qt0pat
circ_sys.pulm_loop.PVN.C.p => pt0pvn
]
prob = ODEProblem(circ_sys, u0, (0.0, 20.0))
##
@time ShiComplexSol = solve(prob, Tsit5(); reltol=1e-6, abstol=1e-9, saveat=19:0.01:20)
# The callbacks prevent saveat from working as intended! So I need to interpolate the results:
ShiComplexSolInt = ShiComplexSol(19:0.01:20)
##
## Read benchmark data and compare
ShiBench = CSV.read("ShiComplex.csv", DataFrame)
@test SciMLBase.successful_retcode(ShiComplexSol)
@test sum((ShiComplexSolInt[circ_sys.heart.LV.V] .- ShiBench[!, :LV_V]) ./ ShiBench[!, :LV_V]) / length(ShiComplexSolInt.u) ≈ 0 atol = 1e-3
@test sum((ShiComplexSolInt[circ_sys.heart.RV.V] .- ShiBench[!, :RV_V]) ./ ShiBench[!, :RV_V]) / length(ShiComplexSolInt.u) ≈ 0 atol = 1e-3
@test sum((ShiComplexSolInt[circ_sys.heart.LA.V] .- ShiBench[!, :LA_V]) ./ ShiBench[!, :LA_V]) / length(ShiComplexSolInt.u) ≈ 0 atol = 1e-3
@test sum((ShiComplexSolInt[circ_sys.heart.RA.V] .- ShiBench[!, :RA_V]) ./ ShiBench[!, :RA_V]) / length(ShiComplexSolInt.u) ≈ 0 atol = 1e-3
##
end
##
@testset "Bjørdalsbakke" begin
##
using ModelingToolkit
using CirculatorySystemModels
# # A simple single-chamber model
#
#  in the `ResistorDiode` element.
#
# [Jupyter Notebook](./BjordalsbakkeModel.ipynb)
# ## Define the parameters
#
# All the parameters are taken from table 1 of [Bjørdalsbakke2022].
#
# Cycle time in seconds
#
τ = 0.85
# Double Hill parameters for the ventricle
#
Eₘᵢₙ = 0.03
Eₘₐₓ = 1.5
n1LV = 1.32
n2LV = 21.9
Tau1fLV = 0.303 * τ
Tau2fLV = 0.508 * τ
# Resistances and Compliances
#
R_s = 1.11
C_sa = 1.13
C_sv = 11.0
# Valve parameters
#
# Aortic valve basic
Zao = 0.033
# Mitral valve basic
Rmv = 0.006
# Inital Pressure (mean cardiac filling pressure)
MCFP = 7.0
# ## Calculating the additional `k` parameter
#
# The ventricle elastance is modelled as:
#
# $$E_{l v}(t)=\left(E_{\max }-E_{\min }\right) e(t)+E_{\min }$$
#
# where $e$ is a double-Hill function, i.e., two Hill-functions, which are multiplied by each other:
#
# $$e(\tau)= k \times \frac{\left(\tau / \tau_1\right)^{n_1}}{1+\left(\tau / \tau_1\right)^{n_1}} \times \frac{1}{1+\left(\tau / \tau_2\right)^{n_2}}$$
#
# $k$ is a scaling factor to assure that $e(t)$ has a maximum of $e(t)_{max} = 1$:
#
# $$k = \max \left(\frac{\left(\tau / \tau_1\right)^{n_1}}{1+\left(\tau / \tau_1\right)^{n_1}} \times \frac{1}{1+\left(\tau / \tau_2\right)^{n_2}} \right)^{-1}$$ .
#
nstep = 1000
t = LinRange(0, τ, nstep)
kLV = 1 / maximum((t ./ Tau1fLV) .^ n1LV ./ (1 .+ (t ./ Tau1fLV) .^ n1LV) .* 1 ./ (1 .+ (t ./ Tau2fLV) .^ n2LV))
# ## Set up the model elements
#
# Set up time as a parameter `t`
#
@independent_variables t
# Heart is modelled as a single chamber (we call it `LV` for "Left Ventricle" so the model can be extended later, if required):
#
@named LV = DHChamber(V₀=0.0, Eₘₐₓ=Eₘₐₓ, Eₘᵢₙ=Eₘᵢₙ, n₁=n1LV, n₂=n2LV, τ=τ, τ₁=Tau1fLV, τ₂=Tau2fLV, k=kLV, Eshift=0.0, inP=true)
# The two valves are simple diodes with a small resistance
# (resistance is needed, since perfect diodes would connect two elastances/compliances, which will lead to unstable oscillations):
#
@named AV = ResistorDiode(R=Zao)
@named MV = ResistorDiode(R=Rmv)
# The main components of the circuit are 1 resistor `Rs` and two compliances for systemic arteries `Csa`,
# and systemic veins `Csv` (names are arbitrary).
#
@named Rs = Resistor(R=R_s)
@named Csa = Compliance(C=C_sa, inP=true, has_ep=true, has_variable_ep=true)
# @named Csv = Compliance(C=C_sv, inV=true, has_ep=true)
@named Csv = Elastance(E=1/C_sv, inP=false)
# _Note: testing different parameters and formulations here. May need to do all of them separately to really do a unit test.
#
# ## Build the system
#
# ### Connections
#
# The system is built using the `connect` function. `connect` sets up the Kirchhoff laws:
#
# - pressures are the same in all connected branches on a connector
# - sum of all flow rates at a connector is zero
#
# The resulting set of Kirchhoff equations is stored in `circ_eqs`:
#
circ_eqs = [
connect(LV.out, AV.in)
connect(AV.out, Csa.in)
connect(Csa.out, Rs.in)
connect(Rs.out, Csv.in)
connect(Csv.out, MV.in)
connect(MV.out, LV.in)
Csa.ep.p ~ 0
]
# ### Add the component equations
#
# In a second step, the system of Kirchhoff equations is completed by the component equations (both ODEs and AEs), resulting in the full, overdefined ODE set `circ_model`.
#
# _Note: we do this in two steps._
#
@named _circ_model = ODESystem(circ_eqs, t)
@named circ_model = compose(_circ_model,
[LV, AV, MV, Rs, Csa, Csv])
# ### Simplify the ODE system
#
# The crucial step in any acausal modelling is the sympification and reduction of the OD(A)E system to the minimal set of equations. ModelingToolkit.jl does this in the `structural_simplify` function.
#
circ_sys = structural_simplify(circ_model)
# `circ_sys` is now the minimal system of equations. In this case it consists of 3 ODEs for the three pressures.
#
# _Note: `structural_simplify` reduces and optimises the ODE system. It is, therefore, not always obvious, which states it will use and which it will drop. We can use the `states` and `observed` function to check this. It is recommended to do this, since small changes can reorder states, observables, and parameters._
#
# States in the system are now:
#unknowns(circ_sys)
# Observed parameters - the system will drop these from the ODE system that is solved, but it keeps all the algebraic equations needed to calculate them in the system object, as well as the `ODEProblem` and solution object - are:
#observed(circ_sys)
# And the parameters (these could be reordered, so check these, too):
#parameters(circ_sys)
# ### Define the ODE problem
#
# First defined initial conditions `u0` and the time span for simulation:
#
u0 = [
LV.p => MCFP
Csa.p => MCFP
Csv.p => MCFP
]
tspan = (0, 20)
# in this case we use the mean cardiac filling pressure as initial condition, and simulate 20 seconds.
#
# Then we can define the problem:
#
prob = ODEProblem(circ_sys, u0, tspan)
# ## Simulate
#
# The ODE problem is now in the MTK/DifferentialEquations.jl format and we can use any DifferentialEquations.jl solver to solve it:
#
@time BBsol = solve(prob, Vern7(), reltol=1e-6, abstol=1e-9, saveat=(19:0.01:20))
# BBsol = sol(19:0.01:20)
BBbench = CSV.read("BB.csv", DataFrame)
@test SciMLBase.successful_retcode(BBsol)
@test sum((BBsol[LV.V] .- BBbench[!, :LV_V]) ./ BBbench[!, :LV_V]) / length(BBsol.u) ≈ 0 atol = 1.5e-3
@test sum((BBsol[Csa.p] .- BBbench[!, :Csa_p]) ./ BBbench[!, :Csa_p]) / length(BBsol.u) ≈ 0 atol = 1.5e-3
@test sum((BBsol[Csv.p] .- BBbench[!, :Csv_p]) ./ BBbench[!, :Csv_p]) / length(BBsol.u) ≈ 0 atol = 1.5e-3
##
end
# Helpers to set up the tests
# df = DataFrame(
# t=ShiSol.t,
# LV_V=ShiSol[Heart.LV.V],
# RV_V=ShiSol[Heart.RV.V],
# LA_V=ShiSol[Heart.LA.V],
# RA_V=ShiSol[Heart.RA.V],
# SAS_S_p=ShiSol[SystLoop.SAS.C.p],
# SAS_L_q=ShiSol[SystLoop.SAS.L.q],
# SAT_S_p=ShiSol[SystLoop.SAT.C.p],
# SAT_L_q=ShiSol[SystLoop.SAT.L.q] oj,
# SVN_C_p=ShiSol[SystLoop.SVN.C.p],
# PAS_S_p=ShiSol[PulmLoop.PAS.C.p],
# PAS_L_q=ShiSol[PulmLoop.PAS.L.q],
# PAT_S_p=ShiSol[PulmLoop.PAT.C.p],
# PAT_L_q=ShiSol[PulmLoop.PAT.L.q],
# PVN_C_p=ShiSol[PulmLoop.PVN.C.p]
# )
# CSV.write("ShiComplex.csv", df)
##
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | docs | 1439 | # CirculatorySystemModels
CirculatorySystemModels.jl is a Julia modelling library, that builds on the ModelingToolkit.jl package, which is part of Julia's SciML framework. It allows efficient and quick implementation of lumped parameter models using an acausal modelling approach. Due to just-in-time compilation and multiple dispatch, models created using this framework achieve a speed-up of one to two orders of magnitude compared to Matlab and Python, and comparable speeds to native C implementations, while using a high-level approach. The library is modular and extensible.
We believe this library will be useful (dare we say, could be a game changer?) for many colleagues working in this field.
[](https://TS-CUBED.github.io/CirculatorySystemModels.jl/stable/)
[](https://TS-CUBED.github.io/CirculatorySystemModels.jl/dev/)
[](https://github.com/TS-CUBED/CirculatorySystemModels.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/TS-CUBED/CirculatorySystemModels.jl)
[](https://doi.org/10.5281/zenodo.7497881)
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | docs | 8316 | ---
title: CirculatorySystemModels.jl - A ModelingToolkit Library for 0D-Lumped-Parameter Models of the Cardiovascular Circulation
tags:
- Julia
- ModelingToolkit
- cardio-vascular
- lumped parameter
- circulation
- acausal
- patient-specific
authors:
- name: Torsten Schenkel
orcid: 0000-0001-5560-1872
equal-contrib: true
affiliation: "1, 2" # (Multiple affiliations must be quoted)
- name: Harry Saxton
orcid: 0000-0001-7433-6154
equal-contrib: true # (This is how you can denote equal contributions between multiple authors)
affiliation: 2
affiliations:
- name: Department of Engineering and Mathematics, Sheffield Hallam University, UK
index: 1
- name: Materials and Engineering Research Institute MERI, Sheffield Hallam University, UK
index: 2
bibliography: paper.bib
---
# Summary
Within the realm of circulatory mechanics, lumped parameter (0D)
modelling [@shi2011review] offers the unique ability to examine both
cardiac function and global hemodynamics within the context of a single
model. Due to the interconnected nature of the cardiovascular system,
being able to quantify both is crucial for the effective prediction and
diagnosis of cardiovascular diseases. Lumped parameter modelling derives
one of its main strengths from the minimal computation time required to
solve ODEs and algebraic equations. Furthermore, the relatively simple
structure of the model allows most personalized simulations to be
automated. Meaning the ability to embed these lumped parameter models
into a clinical workflow could one day become trivial
[@bozkurt2022patient; @holmes2018clinical].
_CirculatorySystemModels.jl_ is a [Julia](https://www.julialang.org) [@bezanson2017julia]
package, built on the acausal modelling framework provided by _ModelingToolkit.jl_
[@ma2021modelingtoolkit], containing all the common elements plus more
needed for effective and realistic lumped parameter modelling. Currently
_CirculatorySystemModels.jl_ supports common elements such as a capacitor,
resistor, inductance and diodes [@westerhof2010snapshots], which act as
simple valve functions. We also make extensions to the common elements
to include constant compliance chambers, non-linear and Poiseuille
resistances [@pfitzner1976poiseuille]. Plus the Double-Hill, and Shi
activation functions which are used as the cardiac driving chamber
elastance's
[@stergiopulos1996determinants; @korakianitis2006numerical].
We also include non-linear valve functions from Shi, and Mynard
[@korakianitis2006numerical; @mynard2012simple].
Alongisde individual components we also have created a collection of sub
compartments including, full circulatory, systemic, pulmonary and heart
models. We then also break down these full systems into collections of
elements such as the famous Windkessel models [@westerhof2009arterial]
to give the user full control over their modelling.
Users can easily add new elements to _CirculatorySystemModels.jl_
using _ModelingToolkit.jl_ functions.
# Statement of need
Lumped parameter modelling has become an essential part of contributing
strongly to our understanding of circulatory physiology. Lumped
parameter models have been used in many different contexts across
cardiovascular medicine such as aortic valve stenosis, neonatal
physiology and detection of coronary artery disease
[@laubscher2022dynamic; @sepulveda2022openmodelica; @dash2022non]. There
already exists some popular packages within both Simulink and Modelica
such as the "Cardiovascular library for lumped-parameter modeling"
[@rosalia2021object] and "Physiolibary" [@matejak2014physiolibrary]
respectively. These languages operate a block orientated "drag and
drop" approach with Modelica been the common choice due to it's acausal
modelling approach [@schweiger2020modeling]. Other languages, based on
XML, exist for lumped parameter modelling such as CellML
[@cuellar2003overview] and SBML [@hucka2003systems], while these are
great for exchanging models they are often difficult to implement and
model analysis is limited. A common theme within all current lumped
parameter modelling software is the systems inability to deal with
complex event handling and non-linear components.
Being based on _ModelingToolkit.jl_, _CirculatorySystemModels.jl_ overcomes
these limitations by leveraging the wider _SciML_ framework.
_CirculatorySystemModels.jl_
provides the Julia community with a quick and effective way to perform
lumped parameter modelling, being the first within the field to leverage
both multiple dispatch and JIT compilation. As a result of Julia's
architecture, as the complexity of the model increases the model
analysis time does not become unreasonable.
Other packages exist which
allow users to import models from other frameworks, CellMLToolkit.jl
[@CellMLToolKit] and OpenModelica.jl [@tinnerholm2022modular].
_CirculatorySystemModels.jl_ goes beyond these by providing a lumped parameter modelling library
with seamless integration with the SciML framework
[@Dixit2022; @rackauckas2020universal; @rackauckas2017differentialequations]
which allows for extensive and efficient model analysis.
Since both the modelling library and the framework it is built on are pure Julia,
new components can be developed in a transparent and consistent manner.
Using Julia, _CirculatorySystemModels.jl_ models compute significantly faster
than models implemented in Matlab or Python, and at the same speed as
specialised C-code (\autoref{tbl:benchmarks}). This allows the models to run in real-time,
and opens the possibility of global parameter optimisation, global sensitivity analysis.
The modular, acausal approach also allows quick and straightforward changes to the
topology of the model, which can be automated using meta-programming techniques.
# Example
Validation and benchmarking was performed on a full, 4-chamber, model of the circulation system
proposed by [@korakianitis2006numerical] (\autoref{fig-shi-diagram}). This model was previously implemented in CellML [@Shi2018],
which makes it an ideal candidate for validation of the new modeling library^[Note that CellML does not allow the callbacks which are required for the
extended valve model, so only the simplified model can be compared. The _CirculatorySystemModels.jl_
implementation of [@korakianitis2006numerical] includes the extended model as well.].
Model results from _CirculatorySystemModels.jl_ model (\autoref{fig:shi-results}) are a perfect match for the CellML model.
The CellML model was run in three versions: (1) imported into _ModelingToolkit.jl_ using _CellMLToolKit.jl_,
(2) Matlab code exported from CellML, (3) Python/SciPy code exported from CellML.
Speedup against Matlab and Python is 2 and 3 orders of magnitude, respectively (\autoref{tbl:benchmarks}).
![4-chamber, full-circulationmodel from [@korakianitis2006numerical]. Groupings in dashed rectangles are implemented as compound subsystems, which in turn have been composed from individual resistor, compliance, and inertance elements. Ventricles and Atria implemented as time-variable elastances. Both simplified and dynamic, non-linear valve models are implemented. \label{fig-shi-diagram}](fig-shi-diagram.pdf){width=100%}
| CirculatorySystemModels.jl | CellMLToolkit.jl | Matlab (ode45) | Python (scipy.solve) |
|:--------------------:|:----------------:|:--------------:|:--------------------:|
| 1x | 1.6x | 272x | 963x |
: Simulation time comparison for a single run of [@korakianitis2006numerical]. CirculatorySystemModels.jl model was implemented from scratch. CellML model was imported into ModelingToolkit.jl using CellMLToolkit.jl, Matlab and Python models were created from the CellML code and downloaded from the [CellML Model Repository](http://models.cellml.org/exposure/c49d416ae3a5132882e6ea7479ba50f5/ModelMain.cellml/view). \label{tbl:benchmarks}
![(a-f) Results for simplified model [@korakianitis2006numerical] implemented in _CirculatorySystemModels.jl_. These results match the results from the CellML models (not shown). \label{fig:shi-results}](fig-shi-results.pdf){width=100%}
# Acknowledgements
Harry Saxton is supported by a Sheffield Hallam University Graduate Teaching Assistant PhD scholarship.
# References {-}
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | docs | 149 | ```@meta
CurrentModule = CirculatorySystemModels
```
## Method Index (AutoDoc)
```@index
```
```@autodocs
Modules = [CirculatorySystemModels]
```
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | docs | 3247 | ```@meta
-
CurrentModule = CirculatorySystemModels
```
# CirculatorySystemModels
Documentation for [CirculatorySystemModels](https://github.com/TS-CUBED/CirculatorySystemModels.jl).
## An acausal modelling library for Circulation Models
CirculatorySystemModels.jl is an acausal modelling library for zero-dimensional, or _lumped parameter_ modelling of the circulatory system for [ModelingToolkit.jl (MTK)](https://github.com/SciML/ModelingToolkit.jl).
Integration into MTK and the [SciML](https://docs.sciml.ai/Overview/stable/) environment enables efficient solver methods ([DifferentialEquations.jl](https://diffeq.sciml.ai/latest/)), local and global parameter optimisation ([Optimization.jl](https://optimization.sciml.ai/stable/)), Sensitivity Analysis ([GlobalSensitivity.jl](https://gsa.sciml.ai/stable/)), and many other features in the SciML framework.
The acausal modelling approach in MTK was chosen to support a "if you can draw it you can model it" paradigm.
The main model states that are modelled throughout these models are:
- _volume flow rate_ (at nodes and through elements): $q\ [\mathrm{cm^{3}/s}]$ ($[\mathrm{ml/s}]$). Flow into an element is positive, flow out of an element is negative.
- _pressure_ (at nodes): $p\ [\mathrm{mm_{{Hg}}}]$.
- _pressure difference_ (over elements): $\Delta p\ [\mathrm{mm_{{Hg}}}]$. The pressure difference is following the usual fluid mechanical definition $\Delta p = p_{out} - p_{in}$. and is usually negative in flow direction!
### Units
There are many unit systems that are used in circulation models.
This modelling system uses the most common one, which uses $\mathrm{mm_{Hg}}$ for pressures and $\mathrm{ml/s}$ or $\mathrm{cm^3/s}$ for flow rates.
This is a variation of the $\mathrm{[g, cm, s]}$ system, which could be called $\mathrm{[g, cm, s, mm_{Hg}]}$ system.
Different model components are developed based on publications that use different unit systems. In those cases we attempted to keep the equations in the published system and do unit conversions transparently within the component function, while the outside API stays in the $\mathrm{[g, cm, s, mm_{Hg}]}$ system.
All model parameters are to be given in the $\mathrm{[g, cm, s, mm_{Hg}]}$ system unless otherwise specified in the component documentation.
### Main variables
The flow is modelled in terms of pressure $p$ and flow $q$. In many 0D
models of the circulation system these are replaced by the electrical
terms of voltage $v$ and current $i$. For this model we want to use the
physiologically relevant parameters. This also avoids the confusion of
using the same symbol $v$ to denote both, potential at a connection, and
the difference in potential over a component, as is commonly done in
electrical analogon models. To denote the pressure drop over a
component, this model uses the symbol $\Delta p$.
Time is the independent variable in all the symbolic operations, so needs to be
defined as such (do not use `t` as a variable name elsewhere!). This can be set using the `@independent_variables` macro.
```julia
@independent_variables t
```
### Compatibility
From version 0.4.0 CirculatorySystemModels is only compatible with Julia 1.10 and up, and with MTK 9 and higher.
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.4.0 | b427a3f71e8dbc850927046e6a323aea46907469 | docs | 8351 | ```@meta
EditURL = "BjordalsbakkeModel.jl"
```
# Importing the required packages
````@example BjordalsbakkeModel
using CirculatorySystemModels
using ModelingToolkit
using OrdinaryDiffEq
using Plots
import DisplayAs
````
# A simple single-chamber model

This follows Bjørdalsbakke et al.
Bjørdalsbakke, N.L., Sturdy, J.T., Hose, D.R., Hellevik, L.R., 2022. Parameter estimation for closed-loop lumped parameter models of the systemic circulation using synthetic data. Mathematical Biosciences 343, 108731. https://doi.org/10.1016/j.mbs.2021.108731
Changes from the published version above:
- Capacitors are replaced by compliances. These are identical to capacitors, but have an additional parameter, the unstrained volume $V_0$, which allows for realistic blood volume modelling.
Compliances have an inlet and an oulet in line with the flow, rather than the ground connector of the dangling capacitor.
- The aortic resistor is combined with the valve (diode) in the `ResistorDiode` element.
[Jupyter Notebook](./BjordalsbakkeModel.ipynb)
## Define the parameters
All the parameters are taken from table 1 of [Bjørdalsbakke2022].
Cycle time in seconds
````@example BjordalsbakkeModel
τ = 0.85
````
Double Hill parameters for the ventricle
````@example BjordalsbakkeModel
Eₘᵢₙ = 0.03
Eₘₐₓ = 1.5
n1LV = 1.32;
n2LV = 21.9;
Tau1fLV = 0.303 * τ;
Tau2fLV = 0.508 * τ
````
Resistances and Compliances
````@example BjordalsbakkeModel
R_s = 1.11
C_sa = 1.13
C_sv = 11.0
````
Valve parameters
Aortic valve basic
````@example BjordalsbakkeModel
Zao = 0.033
````
Mitral valve basic
````@example BjordalsbakkeModel
Rmv = 0.006
````
Inital Pressure (mean cardiac filling pressure)
````@example BjordalsbakkeModel
MCFP = 7.0
````
## Calculating the additional `k` parameter
The ventricle elastance is modelled as:
$$E_{l v}(t)=\left(E_{\max }-E_{\min }\right) e(t)+E_{\min }$$
where $e$ is a double-Hill function, i.e., two Hill-functions, which are multiplied by each other:
$$e(\tau)= k \times \frac{\left(\tau / \tau_1\right)^{n_1}}{1+\left(\tau / \tau_1\right)^{n_1}} \times \frac{1}{1+\left(\tau / \tau_2\right)^{n_2}}$$
and $k$ is a scaling factor to assure that $e(t)$ has a maximum of $e(t)_{max} = 1$:
$$k = \max \left(\frac{\left(\tau / \tau_1\right)^{n_1}}{1+\left(\tau / \tau_1\right)^{n_1}} \times \frac{1}{1+\left(\tau / \tau_2\right)^{n_2}} \right)^{-1}$$
````@example BjordalsbakkeModel
nstep = 1000
t = LinRange(0, τ, nstep)
kLV = 1 / maximum((t ./ Tau1fLV).^n1LV ./ (1 .+ (t ./ Tau1fLV).^n1LV) .* 1 ./ (1 .+ (t ./ Tau2fLV).^n2LV))
````
## Set up the model elements
Set up time as a variable `t`
````@example BjordalsbakkeModel
@variables t
````
Heart is modelled as a single chamber (we call it `LV` for "Left Ventricle" so the model can be extended later, if required):
````@example BjordalsbakkeModel
@named LV = DHChamber(V₀ = 0.0, Eₘₐₓ=Eₘₐₓ, Eₘᵢₙ=Eₘᵢₙ, n₁=n1LV, n₂=n2LV, τ = τ, τ₁=Tau1fLV, τ₂=Tau2fLV, k = kLV, Eshift=0.0)
````
The two valves are simple diodes with a small resistance
(resistance is needed, since perfect diodes would connect two elastances/compliances, which will lead to unstable oscillations):
````@example BjordalsbakkeModel
@named AV = ResistorDiode(R=Zao)
@named MV = ResistorDiode(R=Rmv)
````
The main components of the circuit are 1 resistor `Rs` and two compliances for systemic arteries `Csa`,
and systemic veins `Csv` (names are arbitrary).
_Note: one of the compliances is defined in terms of $dV/dt$ using the option `inV = true`. The other
without that option is in $dp/dt$._
````@example BjordalsbakkeModel
@named Rs = Resistor(R=R_s)
@named Csa = Compliance(C=C_sa)
@named Csv = Compliance(C=C_sv, inP=true)
````
## Build the system
### Connections
The system is built using the `connect` function. `connect` sets up the Kirchhoff laws:
- pressures are the same in all connected branches on a connector
- sum of all flow rates at a connector is zero
The resulting set of Kirchhoff equations is stored in `circ_eqs`:
````@example BjordalsbakkeModel
circ_eqs = [
connect(LV.out, AV.in)
connect(AV.out, Csa.in)
connect(Csa.out, Rs.in)
connect(Rs.out, Csv.in)
connect(Csv.out, MV.in)
connect(MV.out, LV.in)
]
````
### Add the component equations
In a second step, the system of Kirchhoff equations is completed by the component equations (both ODEs and AEs), resulting in the full, overdefined ODE set `circ_model`.
_Note: we do this in two steps._
````@example BjordalsbakkeModel
@named _circ_model = ODESystem(circ_eqs, t)
@named circ_model = compose(_circ_model,
[LV, AV, MV, Rs, Csa, Csv])
````
### Simplify the ODE system
The crucial step in any acausal modelling is the sympification and reduction of the OD(A)E system to the minimal set of equations. ModelingToolkit.jl does this in the `structural_simplify` function.
````@example BjordalsbakkeModel
circ_sys = structural_simplify(circ_model)
````
`circ_sys` is now the minimal system of equations. In this case it consists of 3 ODEs for the ventricular volume and the systemic and venous pressures.
_Note: this reduces and optimises the ODE system. It is, therefore, not always obvious, which states it will use and which it will drop. We can use the `states` and `observed` function to check this. It is recommended to do this, since small changes can reorder states, observables, and parameters._
States in the system are now:
````@example BjordalsbakkeModel
unknowns(circ_sys)
````
Observed variables - the system will drop these from the ODE system that is solved, but it keeps all the algebraic equations needed to calculate them in the system object, as well as the `ODEProblem` and solution object - are:
````@example BjordalsbakkeModel
observed(circ_sys)
````
And the parameters (these could be reordered, so check these, too):
````@example BjordalsbakkeModel
parameters(circ_sys)
````
### Define the ODE problem
First defined initial conditions `u0` and the time span for simulation:
_Note: the initial conditions are defined as a parameter map, rather than a vector, since the parameter map allows for changes in order.
This map can include non-existant states (like `LV.p` in this case), which allows for exchanging the compliances or the ventricle
for one that's defined in terms of $dp/dt$)._
````@example BjordalsbakkeModel
u0 = [
LV.p => MCFP
LV.V => MCFP/Eₘᵢₙ
Csa.p => MCFP
Csa.V => MCFP*C_sa
Csv.p => MCFP
Csv.V => MCFP*C_sv
]
````
````@example BjordalsbakkeModel
tspan = (0, 20)
````
in this case we use the mean cardiac filling pressure as initial condition, and simulate 20 seconds.
Then we can define the problem:
````@example BjordalsbakkeModel
prob = ODEProblem(circ_sys, u0, tspan)
````
## Simulate
The ODE problem is now in the MTK/DifferentialEquations.jl format and we can use any DifferentialEquations.jl solver to solve it:
````@example BjordalsbakkeModel
sol = solve(prob, Vern7(), reltol=1e-12, abstol=1e-12);
nothing #hide
````
## Results
````@example BjordalsbakkeModel
p1 = plot(sol, idxs=[LV.p, Csa.in.p], tspan=(16 * τ, 17 * τ), xlabel = "Time [s]", ylabel = "Pressure [mmHg]", hidexaxis = nothing) # Make a line plot
p2 = plot(sol, idxs=[LV.V], tspan=(16 * τ, 17 * τ),xlabel = "Time [s]", ylabel = "Volume [ml]", linkaxes = :all)
p3 = plot(sol, idxs=[Csa.in.q,Csv.in.q], tspan=(16 * τ, 17 * τ),xlabel = "Time [s]", ylabel = "Flow rate [ml/s]", linkaxes = :all)
p4 = plot(sol, idxs=(LV.V, LV.p), tspan=(16 * τ, 17 * τ),xlabel = "Volume [ml]", ylabel = "Pressure [mmHg]", linkaxes = :all)
img = plot(p1, p2, p3, p4; layout=@layout([a b; c d]), legend = true)
img = DisplayAs.Text(DisplayAs.PNG(img))
img
````
---
*This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
| CirculatorySystemModels | https://github.com/TS-CUBED/CirculatorySystemModels.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | code | 238 | using Documenter
using ContextVariablesX
makedocs(
sitename = "ContextVariablesX",
format = Documenter.HTML(),
modules = [ContextVariablesX],
)
deploydocs(; repo = "github.com/tkf/ContextVariablesX.jl", push_preview = true)
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | code | 10572 | module ContextVariablesX
# Re-exporting `Base` functions so that Documenter knows what's public:
export @contextvar, ContextVar, get, getindex, snapshot_context, with_context
using Logging: AbstractLogger, Logging
using UUIDs: UUID, UUIDs, uuid4
if isdefined(UUIDs, :uuid5)
using UUIDs: uuid5
else
using Compat: uuid5
end
include("payloadlogger.jl")
function _ContextVar end
# `ContextVar` object itself does not hold any data (except the
# default value). It is actually just a key into the task-local
# context storage.
"""
ContextVar{T}
Context variable type. This is the type of the object `var` created by
[`@contextvar var`](@ref @contextvar). This acts as a reference to the
value stored in a task-local context. The macro `@contextvar` is the only
public API to construct this object.
!!! warning
It is unspecified if this type is concrete or not. It may be
changed to an abstract type and/or include more type parameters in
the future.
"""
struct ContextVar{T}
name::Symbol
_module::Module
key::UUID
has_default::Bool
default::T
global _ContextVar
_ContextVar(name, _module, key, ::Type{T}, default) where {T} =
new{T}(name, _module, key, true, default)
_ContextVar(name, _module, key, ::Type{T}) where {T} = new{T}(name, _module, key, false)
end
_ContextVar(name, _module, key, ::Nothing, default) =
_ContextVar(name, _module, key, typeof(default), default)
_ContextVar(name, _module, key, ::Nothing) = _ContextVar(name, _module, key, Any)
#=
baremodule _EmptyModule end
ContextVar{T}(name::Symbol, default) where {T} =
_ContextVar(name, _EmptyModule, uuid4(), T, default)
ContextVar{T}(name::Symbol) where {T} = _ContextVar(name, _EmptyModule, uuid4(), T)
ContextVar(name::Symbol, default) = ContextVar{typeof(default)}(name, default)
ContextVar(name::Symbol) = ContextVar{Any}(name)
"""
ContextVar{T}(name::Symbol [, default])
ContextVar(name::Symbol [, default])
Define *local* context variable.
!!! warning
Using this constructor to define context variable in the global name space
(i.e., `const var = ContextVar(:var)`) is not recommended because this is not
safe to be used with Distribute.jl. Use `@contextvar var` instead.
"""
ContextVar
=#
Base.eltype(::Type{ContextVar{T}}) where {T} = T
function Base.show(io::IO, var::ContextVar)
print(io, ContextVar)
if eltype(var) !== Any && !(var.has_default && typeof(var.default) === eltype(var))
print(io, '{', eltype(var), '}')
end
print(io, '(', repr(var.name))
if var.has_default
print(io, ", ")
show(io, var.default)
end
print(io, ')')
end
function Base.show(io::IO, ::MIME"text/plain", var::ContextVar)
print(io, var._module, '.', var.name, " :: ContextVar")
if get(io, :compact, false) === false
print(io, " [", var.key, ']')
if get(var) === nothing
print(io, " (not assigned)")
else
print(io, " => ")
show(IOContext(io, :compact => true), MIME"text/plain"(), var[])
end
end
end
# The primitives that can be monkey-patched to play with new context
# variable storage types:
"""
merge_ctxvars(ctx::Union{Nothing,T}, kvs) -> ctx′:: Union{Nothing,T}
!!! warning
This is not a public API. This documentation is for making it easier to
experiment with different implementations of the context variable storage
backend, by monkey-patching it at run-time. When this function is
monkey-patched, `ctxvars_type` should also be monkey-patched to return
the type `T`.
The first argument `ctx` is either `nothing` or a dict-like object of type `T` where
its `keytype` is `UUID` and `valtype` is `Any`. The second argument `kvs` is an
iterable of `Pair{UUID,<:Union{Some,Nothing}}` values. Iterable `kvs` must have
length.
If `ctx` is `nothing` and `kvs` is non-empty, `merge_ctxvars` creates a new
instance of `T`. If `ctx` is not `nothing`, it returns a shallow-copy `ctx′` of
`ctx` where `k => v` is inserted to `ctx′` for each `k => Some(v)` in `kvs`
and `k` is deleted from `ctx′` for each `k => nothing` in `kvs`.
"""
function merge_ctxvars(ctx, kvs)
# Assumption: eltype(kvs) <: Pair{UUID,<:Union{Some,Nothing}}
if isempty(kvs)
return ctx
else
# Copy-or-create-on-write:
vars = ctx === nothing ? ctxvars_type()() : copy(ctx)
for (k, v) in kvs
if v === nothing
delete!(vars, k)
else
vars[k] = something(v)
end
end
isempty(vars) && return nothing # should we?
return vars
end
end
ctxvars_type() = Dict{UUID,Any}
_ctxvars_type() = Union{Nothing,ctxvars_type()}
get_task_ctxvars() = _get_task_ctxvars()::_ctxvars_type()
new_merged_ctxvars(kvs) =
merge_ctxvars(
get_task_ctxvars(),
(
k.key => v === nothing ? v : Some(convert(eltype(k), something(v)))
for (k, v) in kvs
),
)::_ctxvars_type()
struct _NoValue end
"""
get(var::ContextVar{T}) -> Union{Some{T},Nothing}
Return `Some(value)` if `value` is assigned to `var`. Return `nothing` if
unassigned.
"""
function Base.get(var::ContextVar{T}) where {T}
ctx = get_task_ctxvars()
if ctx === nothing
var.has_default && return Some(var.default)
return nothing
end
if var.has_default
return Some(get(ctx, var.key, var.default)::T)
else
y = get(ctx, var.key, _NoValue())
y isa _NoValue || return Some(ctx[var.key]::T)
end
return nothing
end
"""
getindex(var::ContextVar{T}) -> value::T
Return the `value` assigned to `var`. Throw a `KeyError` if unassigned.
"""
function Base.getindex(var::ContextVar{T}) where {T}
maybe = get(var)
maybe === nothing && throw(KeyError(var))
return something(maybe)::T
end
"""
genkey(__module__::Module, varname::Symbol) -> Union{UUID,Nothing}.
Generate a stable UUID for a context variable `__module__.\$varname`.
"""
function genkey(__module__::Module, varname::Symbol)
fullpath = push!(collect(fullname(__module__)), varname)
if any(x -> occursin(".", string(x)), fullpath)
throw(ArgumentError(
"Modules and variable names must not contain a dot:\n" * join(fullpath, "\n"),
))
end
pkgid = Base.PkgId(__module__)
if pkgid.uuid === nothing
return nothing
end
return uuid5(pkgid.uuid, join(fullpath, '.'))
end
"""
@contextvar var[::T] [= default]
Declare a context variable named `var`. The type constraint `::T` and
the default value `= default` are optional. If the default value is given
without the type constraint `::T`, its type `T = typeof(default)` is used.
!!! warning
Context variables defined outside a proper package does not work
with `Distributed`.
# Examples
Top-level context variables needs to be declared in a package:
```julia
module MyPackage
@contextvar cvar1
@contextvar cvar2 = 1
@contextvar cvar3::Int
end
```
"""
macro contextvar(ex0)
ex = ex0
if Meta.isexpr(ex, :(=))
length(ex.args) != 2 && throw(ArgumentError("Unsupported syntax:\n$ex0"))
ex, default = ex.args
args = Any[esc(default)]
else
args = []
end
if Meta.isexpr(ex, :(::))
length(ex.args) != 2 && throw(ArgumentError("Malformed input:\n$ex0"))
ex, vartype = ex.args
pushfirst!(args, esc(vartype))
else
pushfirst!(args, nothing)
end
if !(ex isa Symbol)
if ex === ex0
throw(ArgumentError("Unsupported syntax:\n$ex0"))
else
throw(ArgumentError("""
Not a variable name:
$ex
Input:
$ex0
"""))
end
end
varname = QuoteNode(ex)
key = genkey(__module__, ex)
if key === nothing
if isinteractive() && _WARN_DYNAMIC_KEY[]
@warn (
"Using `@contextvar` outside a package is discouraged except" *
" for interactive exploration or quick scripts. Context" *
" variables created outside a proper package do not have " *
" consistent ID and cannot be used with `Distributed`."
) maxlog=1
end
# Creating a UUID at macro expansion time because:
# * It would be a memory leak it were created at run-time because
# context variable storage can be filled with UUIDs created at
# run-time.
# * Creating it at run-time is doable with function-based interface like
# `ContextVar(:name, default)`.
key = uuid4()
end
return Expr(
:const,
:($(esc(ex)) = _ContextVar($varname, $__module__, $key, $(args...))),
)
end
# A hack to make doctest easier
const _WARN_DYNAMIC_KEY = Ref(true)
"""
with_context(f, var1 => value1, var2 => value2, ...)
with_context(f, pairs)
Run `f` in a context with given values set to the context variables. Variables
specified in this form are rolled back to the original value when `with_context`
returns. It act like a dynamically scoped `let`. If `nothing` is passed as
a value, corresponding context variable is cleared; i.e., it is unassigned or
takes the default value. Use `Some(value)` to set `value` if `value` can be
`nothing`.
with_context(f, nothing)
Run `f` in a new empty context. All variables are rewind to the original values
when `with_context` returns.
Note that
```julia
var2[] = value2
with_context(var1 => value1) do
@show var2[] # shows value2
var3[] = value3
end
@show var3[] # shows value3
```
and
```julia
var2[] = value2
with_context(nothing) do
var1[] = value1
@show var2[] # shows default (or throws)
var3[] = value3
end
@show var3[] # does not show value3
```
are not equivalent.
"""
with_context
with_context(f, kvs::Pair{<:ContextVar}...) = with_task_ctxvars(f, new_merged_ctxvars(kvs))
with_context(f, ::Nothing) = with_task_ctxvars(f, nothing)
struct ContextSnapshot{T}
vars::T
end
# TODO: Do we need to implement `Dict{ContextVar}(::ContextSnapshot)`?
# This requires storing UUID-to-ContextVar mapping somewhere.
"""
snapshot_context() -> snapshot::ContextSnapshot
Get a snapshot of a context that can be passed to [`with_context`](@ref) to
run a function inside the current context at later time.
"""
snapshot_context() = ContextSnapshot(get_task_ctxvars())
with_context(f, snapshot::ContextSnapshot) = with_task_ctxvars(f, snapshot.vars)
end # module
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | code | 1661 | struct ContextPayloadLogger <: AbstractLogger
logger::AbstractLogger
ctxvars::Any
end
function _get_task_ctxvars()
logger = Logging.current_logger()
if logger isa ContextPayloadLogger
return logger.ctxvars
end
return nothing
end
function with_task_ctxvars(f, ctx)
@nospecialize
return Logging.with_logger(f, ContextPayloadLogger(current_logger(), ctx))
end
# Forward actual logging interface:
Logging.handle_message(payload::ContextPayloadLogger, args...; kwargs...) =
Logging.handle_message(payload.logger, args...; kwargs...)
Logging.shouldlog(payload::ContextPayloadLogger, args...) =
Logging.shouldlog(payload.logger, args...)
Logging.min_enabled_level(payload::ContextPayloadLogger, args...) =
Logging.min_enabled_level(payload.logger, args...)
Logging.catch_exceptions(payload::ContextPayloadLogger, args...) =
Logging.catch_exceptions(payload.logger, args...)
"""
ContextVariablesX.with_logger(f, logger::AbstractLogger)
Like `Logging.with_logger` but properly propagate the context variables.
"""
function with_logger(f, logger::AbstractLogger)
@nospecialize
cpl = Logging.current_logger()
if cpl isa ContextPayloadLogger
ctx = cpl.ctxvars
else
ctx = nothing
end
return Logging.with_logger(f, ContextPayloadLogger(logger, ctx))
end
"""
ContextVariablesX.current_logger() -> logger::AbstractLogger
Like `Logging.current_logger` but unwraps `ContextPayloadLogger`.
"""
function current_logger()
logger = Logging.current_logger()
if logger isa ContextPayloadLogger
return logger.logger
else
return logger
end
end
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | code | 2884 | module TestContextVariablesX
using Documenter: doctest
using ContextVariablesX
using Test
@contextvar cvar1 = 42
@contextvar cvar2::Int
@contextvar cvar3
@contextvar cvar4::Union{Missing,Int64} = 1
@testset "typed, w/ default" begin
ok = Ref(0)
@sync @async begin
with_context() do
@test cvar1[] == 42
with_context(cvar1 => 0) do
@test cvar1[] == 0
ok[] += 1
@async begin
@test cvar1[] == 0
ok[] += 1
end
with_context(cvar1 => 1) do
@test cvar1[] == 1
ok[] += 1
end
@test cvar1[] == 0
ok[] += 1
end
end
end
@test ok[] == 4
end
@testset "typed, w/o default" begin
with_context() do
@test_throws InexactError with_context(cvar2 => 0.5) do
end
@test_throws KeyError cvar2[]
with_context(cvar2 => 1.0) do
@test cvar2[] === 1
end
end
end
@testset "untyped, w/o default" begin
with_context(cvar3 => 1) do
@test cvar3[] === 1
with_context(cvar3 => 'a') do
@test cvar3[] === 'a'
end
end
end
@testset "show" begin
@test endswith(sprint(show, cvar1), "ContextVar(:cvar1, 42)")
@test endswith(sprint(show, cvar2), "ContextVar{$Int}(:cvar2)")
@test endswith(sprint(show, cvar3), "ContextVar(:cvar3)")
@test endswith(sprint(show, cvar4), "ContextVar{Union{Missing, Int64}}(:cvar4, 1)")
end
@testset "invalid name" begin
name = Symbol("name.with.dots")
err = try
@eval @contextvar $name
nothing
catch err_
err_
end
@test err isa Exception
@test occursin("Modules and variable names must not contain a dot", sprint(showerror, err))
end
@testset "logging: keyword argument" begin
logs, _ = Test.collect_test_logs() do
@sync @async begin
with_context() do
try
error(1)
catch err
@error "hello" exception = (err, catch_backtrace())
end
end
end
end
l, = logs
@test l.message == "hello"
@test haskey(l.kwargs, :exception)
exception = l.kwargs[:exception]
@test exception isa Tuple{Exception,typeof(catch_backtrace())}
@test exception[1] == ErrorException("1")
end
@testset "with_logger" begin
logger = Test.TestLogger()
with_context(cvar1 => 111) do
ContextVariablesX.with_logger(logger) do
@test ContextVariablesX.current_logger() isa Test.TestLogger
@test cvar1[] == 111
@info "hello"
end
end
l, = logger.logs
@test l.message == "hello"
end
@testset "doctest" begin
doctest(ContextVariablesX)
end
end # module
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | docs | 567 | # ContextVariablesX
[](https://tkf.github.io/ContextVariablesX.jl/dev)
[](https://github.com/tkf/ContextVariablesX.jl/actions?query=workflow%3ARun+tests)
ContextVariablesX.jl is a working proof-of-context framework for
propagating context-dependent information to child tasks. See
[RFC: Context variables by tkf · Pull Request #35833 · JuliaLang/julia](https://github.com/JuliaLang/julia/pull/35833)
for discussion.
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | docs | 6474 | # ContextVariablesX.jl
ContextVariablesX.jl is heavily inspired by
[`contextvars`](https://docs.python.org/3/library/contextvars.html) in
Python (see also
[PEP 567](https://www.python.org/dev/peps/pep-0567/)).
## Tutorial
### Basic usage
Context variables can be used to manage task-local states that are
inherited to child tasks. Context variables are created by
[`@contextvar`](@ref):
```julia
@contextvar cvar1 # untyped, without default
@contextvar cvar2 = 1 # typed (Int), with default
@contextvar cvar3::Int # typed, without default
```
Note that running above code in REPL will throw an error because this
form work only within a package namespace. To play with `@contextvar`
in REPL, you can prefix the variable name with `global`:
```@meta
DocTestSetup = quote
using ContextVariablesX
ContextVariablesX._WARN_DYNAMIC_KEY[] = false
function display(x)
show(stdout, "text/plain", x)
println()
end
end
```
```jldoctest tutorial
julia> @contextvar x::Any = 1;
```
!!! warning
`@contextvar` outside a proper package should be used only for
interactive exploration, quick scripting, and testing. Using
`@contextvar` outside packages make it impossible to work with
serialization-based libraries such as Distributed.
You can be get a context variable with indexing syntax `[]`
```jldoctest tutorial
julia> x[]
1
```
It's not possible to set a context variable. But it's possible to run
code inside a new context with new values bound to the context
variables:
```jldoctest tutorial
julia> with_context(x => 100) do
x[]
end
100
```
### Dynamic scoping
[`with_context`](@ref) can be used to set multiple context variables at once,
run a function in this context, and then rollback them to the original state:
```jldoctest tutorial
julia> @contextvar y = 1;
@contextvar z::Int;
```
```jldoctest tutorial
julia> function demo1()
@show x[]
@show y[]
@show z[]
end;
julia> with_context(demo1, x => :a, z => 0);
x[] = :a
y[] = 1
z[] = 0
```
Note that `with_context(f, x => nothing, ...)` clears the value of
`x`, rather than setting the value of `x` to `nothing`. Use
`Some(nothing)` to set `nothing`. Similar caution applies to
`set_context` (see below).
```jldoctest tutorial
julia> with_context(x => Some(nothing), y => nothing, z => nothing) do
@show x[]
@show y[]
@show get(z)
end;
x[] = nothing
y[] = 1
get(z) = nothing
```
Thus,
```julia
with_context(x => Some(a), y => Some(b), z => nothing) do
...
end
```
can be used considered as a dynamically scoped version of
```julia
let x′ = a, y′ = b, z′
...
end
```
Use `with_context(f, nothing)` to create an empty context and rollback the entire
context to the state just before calling it.
```jldoctest tutorial
julia> with_context(y => 100) do
@show y[]
with_context(nothing) do
@show y[]
end
end;
y[] = 100
y[] = 1
```
### Snapshot
A handle to the snapshot of the current context can be obtained with
[`snapshot_context`](@ref). It can be later restored by [`with_context`](@ref).
```jldoctest tutorial
julia> x[]
1
julia> snapshot = snapshot_context();
julia> with_context(x => 100) do
with_context(snapshot) do
@show x[]
end
end;
x[] = 1
```
### Concurrent access
The context is inherited to the child task when the task is created.
Thus, changes made after `@async`/`@spawn` or changes made in other tasks are
not observable:
```julia
julia> function demo2()
x0 = x[]
with_context(x => x0 + 1) do
(x0, x[])
end
end
julia> with_context(x => 1) do
@sync begin
t1 = @async demo2()
t2 = @async demo2()
result = demo2()
[result, fetch(t1), fetch(t2)]
end
end
3-element Array{Tuple{Int64,Int64},1}:
(1, 2)
(1, 2)
(1, 2)
```
In particular, manipulating context variables using the public API is always
data-race-free.
!!! warning
If a context variable holds a mutable value, it is a data-race to mutate the
_value_ when other threads are reading it.
```julia
@contextvar local x = [1] # mutable value
@sync begin
@spawn begin
value = x[] # not a data-race
push!(value, 2) # data-race
end
@spawn begin
value = x[] # not a data-race
@show last(value) # data-race
end
end
```
### Namespace
Consider "packages" and modules with the same variable name:
```jldoctest tutorial
julia> module PackageA
using ContextVariablesX
@contextvar x = 1
module SubModule
using ContextVariablesX
@contextvar x = 2
end
end;
julia> module PackageB
using ContextVariablesX
@contextvar x = 3
end;
```
These packages define are three _distinct_ context variables
`PackageA.x`, `PackageA.SubModule.x`, and `PackageB.x` that can be
manipulated independently.
This is simply because `@contextvar` creates independent variable "instance"
in each context. It can be demonstrated easily in the REPL:
```jldoctest tutorial; filter = r"(^(.*?\.)?x)|(\[.*?\])"m
julia> PackageA.x
Main.PackageA.x :: ContextVar [668bafe1-c075-48ae-a52d-13543cf06ddb] => 1
julia> PackageA.SubModule.x
Main.PackageA.SubModule.x :: ContextVar [0549256b-1914-4fcd-ac8e-33f377be816e] => 2
julia> PackageB.x
Main.PackageB.x :: ContextVar [ddd3358e-a77f-44c0-be28-e5dde929c6f5] => 3
julia> (PackageA.x[], PackageA.SubModule.x[], PackageB.x[])
(1, 2, 3)
julia> with_context(PackageA.x => 10, PackageA.SubModule.x => 20, PackageB.x => 30) do
display(PackageA.x)
display(PackageA.SubModule.x)
display(PackageB.x)
(PackageA.x[], PackageA.SubModule.x[], PackageB.x[])
end
Main.PackageA.x :: ContextVar [668bafe1-c075-48ae-a52d-13543cf06ddb] => 10
Main.PackageA.SubModule.x :: ContextVar [0549256b-1914-4fcd-ac8e-33f377be816e] => 20
Main.PackageB.x :: ContextVar [ddd3358e-a77f-44c0-be28-e5dde929c6f5] => 30
(10, 20, 30)
```
```@meta
DocTestSetup = nothing
```
## Reference
```@autodocs
Modules = [ContextVariablesX]
Private = false
```
```@docs
ContextVariablesX.with_logger
ContextVariablesX.current_logger
```
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"MIT"
] | 0.1.3 | 25cc3803f1030ab855e383129dcd3dc294e322cc | docs | 75 | # Internals
```@autodocs
Modules = [ContextVariablesX]
Public = false
```
| ContextVariablesX | https://github.com/tkf/ContextVariablesX.jl.git |
|
[
"Apache-2.0"
] | 1.0.0 | 5682158c5200c4568df03a58f17d2416c1c84486 | code | 3928 | """
HDF5Logger
Creates an object for logging frames of data to an HDF5 file. The frames are
expected to have the same size, and the total number of frames to log is
expected to be known in advance. It currently works with scalars, vectors, and
matrices of basic types that the HDF5 package supports.
# Example 1: Logging a Vector over Time
```julia
log = Log("my_file.h5") # Create a logger.
num_frames = 100 # Set the total number of frames to log.
example_data = [1., 2., 3.] # Create an example of a frame of data.
add!(log, "/a_vector", example_data, num_frames) # Create the stream.
log!(log, "/a_vector", [4., 5., 6.]) # Log a single frame of data.
log!(log, "/a_vector", [7., 8., 9.]) # Log the next frame.
close!(log) # Always clean up when done. Use try-catch to make sure.
# Read it back out using the regular HDF5 library.
using HDF5
x = HDF5.h5open("my_file.h5", "r") do logs
read(logs, "/a_vector")
end
```
# Example 2: Logging a Scalar over Time
The underlying HDF5 library (HDF5.jl) logs things as arrays, so passing in
scalars will result in 1-by-n arrays in the HDF5 file, instead of an n-length
Vector. One can retrieve the n-length Vector by using `squeeze`. E.g.:
```julia
log = Log("my_file.h5") # Create a logger.
add!(log, "/a_scalar", 0., 1000) # Create stream with space for 1000 samples.
log!(log, "/a_scalar", 0.1) # Log a single frame of data.
log!(log, "/a_scalar", 0.2) # Log the next frame.
close!(log) # Always clean up when done. Use try-catch to make sure.
# Read it back out using the regular HDF5 library.
using HDF5
t = HDF5.h5open("my_file.h5", "r") do logs
read(logs, "/a_scalar")
end # t is now a 1-by-1000 Array.
t = squeeze(t, 1) # Make an n-element Vector.
```
# Notes
One often needs to `log!` immediately after an `add!`, so the `add!` function
can also log its example data as the first frame for convenience. Just use:
```julia
add!(log, "/group/name", data, num_frames, true) # Add stream; log data.
```
"""
module HDF5Logger
using HDF5
export Log, add!, log!, close!
mutable struct Stream
count::Int64
length::Int64
rank::Int64
dataset::HDF5Dataset
end
struct Log
streams::Dict{String,Stream}
file_id::HDF5File
function Log(file_name::String)
new(Dict{String,Stream}(), h5open(file_name, "w"))
end
end
function prepare_group!(log::Log, slug::String)
groups = filter(x->!isempty(x), split(slug, '/')) # Explode to group names
group_id = g_open(log.file_id, "/") # Start at top group
for k = 1:length(groups)-1 # For each group up to dataset
if exists(group_id, String(groups[k]))
group_id = g_open(group_id, String(groups[k]))
else
group_id = g_create(group_id, String(groups[k]))
end
end
return (group_id, String(groups[end])) # Group ID and name of dataset
end
function add!(log::Log, slug::String, data, num_samples::Int64, keep::Bool = false)
dims = isbits(data) ? 1 : size(data)
group_id, group_name = prepare_group!(log, slug)
dataset_id = d_create(group_id, group_name,
datatype(eltype(data)),
dataspace(dims..., num_samples))
log.streams[slug] = Stream(0, num_samples, length(dims), dataset_id)
if keep
log!(log, slug, data)
end
end
function log!(log::Log, slug::String, data)
@assert(haskey(log.streams, slug),
"The logger doesn't have that key. Perhaps you need to `add` it?")
@assert(log.streams[slug].count < log.streams[slug].length,
"We've already used up all of the allocated space for this stream!")
log.streams[slug].count += 1
colons = (Colon() for i in 1:log.streams[slug].rank)
log.streams[slug].dataset[colons..., log.streams[slug].count] = data
end
function close!(log::Log)
close(log.file_id)
end
end # module
| HDF5Logger | https://github.com/tuckermcclure/HDF5Logger.jl.git |
|
[
"Apache-2.0"
] | 1.0.0 | 5682158c5200c4568df03a58f17d2416c1c84486 | code | 1900 | using HDF5Logger
using Test
using HDF5 # For reading in wholesale time histories
# Set up some data to work with.
num_samples = 5
vector_data = [1., 2., 3.]
matrix_data = transpose([1 2 3; 4 5 6])
scalar_data = 1.
c = 2
# Create the log.
file_name = "test_log.h5"
log = Log(file_name)
try
# Test a vector
add!(log, "/vector", vector_data, num_samples)
log!(log, "/vector", vector_data)
log!(log, "/vector", c * vector_data)
# Test a matrix
add!(log, "/group/matrix", matrix_data, num_samples, true) # Keep data.
# log!(log, "/group/matrix", matrix_data) # First sample is kept this time!
log!(log, "/group/matrix", c * matrix_data)
# Test a scalar
add!(log, "/group/scalar", scalar_data, num_samples)
log!(log, "/group/scalar", scalar_data)
log!(log, "/group/scalar", c * scalar_data)
catch err
close!(log)
rethrow(err)
end
close!(log)
# Now test that the right stuff happened. Use the regular HDF5 library to open
# the files we created. With the `do` block, the file will be automatically
# closed if anything goes wrong.
h5open(file_name, "r") do file
vector_result = read(file, "/vector")
matrix_result = read(file, "/group/matrix")
scalar_result = read(file, "/group/scalar")
@test(vector_result[:,1] == vector_data)
@test(matrix_result[:,:,1] == matrix_data)
@test(scalar_result[1] == scalar_data)
@test(vector_result[:,2] == c * vector_data)
@test(matrix_result[:,:,2] == c * matrix_data)
@test(scalar_result[2] == c * scalar_data)
@test(size(vector_result) == (3, num_samples))
@test(size(matrix_result) == (3, 2, num_samples))
@test(size(scalar_result) == (1, num_samples))
@test(eltype(vector_result) == Float64)
@test(eltype(matrix_result) == Int64)
@test(eltype(scalar_result) == Float64)
end
# Clean up after ourselves.
rm(file_name)
| HDF5Logger | https://github.com/tuckermcclure/HDF5Logger.jl.git |
|
[
"Apache-2.0"
] | 1.0.0 | 5682158c5200c4568df03a58f17d2416c1c84486 | docs | 2441 | # HDF5Logger
[](https://travis-ci.org/tuckermcclure/HDF5Logger.jl)
[](https://ci.appveyor.com/project/tuckermcclure/hdf5logger-jl)
[](http://codecov.io/github/tuckermcclure/HDF5Logger.jl?branch=master)
<!-- [](https://coveralls.io/github/tuckermcclure/HDF5Logger.jl?branch=master) -->
This package creates a logger for storing individual frames of data over time. The frames can be scalars or arrays of any dimension, and the size must be fixed from sample to sample. Further, the total number of samples to log for each source must be known in advance. This keeps the logging very fast. It's useful, for instance, when one is running a simulation, some value in the sim needs to be logged every X seconds, and the end time of the simulation is known, so the total number of samples that will be needed is also known.
## Simple Example
Create a logger. This actually creates and opens the HDF5 file.
```julia
using HDF5Logger
log = Log("my_log.h5")
```
Add a couple of streams. Suppose we'll log a 3-element gyro reading and a 3-element accelerometer signal each a total of 100 times.
```julia
num_samples = 100
example_gyro_reading = [0., 0., 0.]
example_accel_reading = [0., 0., 0.]
# Preallocate space for these signals.
add!(log, "/sensors/gyro", example_gyro_reading, num_samples)
add!(log, "/sensors/accel", example_accel_reading, num_samples)
```
Log the first sample of each.
```julia
log!(log, "/sensors/gyro", [1., 2., 3.])
log!(log, "/sensors/accel", [4., 5., 6.])
# We can now log to each of these signals 99 more times.
```
Always clean up.
```julia
close!(log);
```
Did that work?
```julia
using HDF5 # Use the regular HDF5 package to load what we logged.
h5open("my_log.h5", "r") do file
gyro_data = read(file, "/sensors/gyro")
accel_data = read(file, "/sensors/accel")
display(gyro_data[:,1])
display(accel_data[:,1])
end
```
```
3-element Array{Float64,1}:
1.00
2.00
3.00
3-element Array{Float64,1}:
4.00
5.00
6.00
```
Yep!
The same process works with scalars, matrices, integers, etc.
| HDF5Logger | https://github.com/tuckermcclure/HDF5Logger.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 72 | # this file is only used for testing - do not remove
Pair{String,Any}[]
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 148 |
Dict(
"T1" => "T1 - empty",
"T2" => "T2 - empty",
"T3" => "T3 - empty",
"T4" => "T4 - empty",
"T5" => "T5 - empty",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 148 |
Dict(
"T1" => "T1 - empty",
"T2" => "T2 - empty",
"T3" => "T3 - empty",
"T4" => "T4 - empty",
"T5" => "T5 - empty",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 37 |
Dict( "hello" => "Hallo Latn de")
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 72 | # this file is only used for testing - do not remove
Pair{String,Any}[]
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 47 |
# wrong key type of dictionary
Dict( 1 => 2 )
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 25 |
"wrong type of object"
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 44 |
# error to envoke warning message
Dict(1)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 109 |
Dict(
"T2" => "T2 - en",
"T3" => "T3 - en",
"T4" => "T4 - en",
"T5" => "T5 - en",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 92 |
[
"T4" => "T4 - en_Latn",
"T5" => "T5 - en_Latn",
"T6" => "T6 - en_Latn",
]
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 45 |
Dict(
"T5" => "T5 - en_Latn_US",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 595 |
(
"" => "Plural-Forms: nplurals=3; plural = n == 1 ? 0 : n == 0 ? 1 : 2",
"T3" => "T3 - en_US",
"T5" => "T5 - en_US",
"T6" => "T6 - en_US",
"T7" => "T7 - en_US",
raw"original $(1)($(2)) : $(3)" => raw"US version $(3) / $(2) $(1)",
raw"These are $(1) houses" => [raw"""This is a house""",
raw"""This is not a house""",
raw"""These are at least $(1) houses""",],
"error1" => ["error1 $(1)"],
raw"error2 $(1)" => ["error2a", "error2b"],
raw"missing argument value $(1)" => String[],
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 246 |
Dict(
"" => "Plural-Forms: nplurals=2; plural = n > 1",
"hello" => "c'a va t'il - fr",
raw"These are $(1) houses" => [ raw"C'est $(1) maison",
raw"Ce sont beaucoup($(1)) de maisons",]
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 36 |
Dict(
"hello" => "cava FR"
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 40 | Dict(
"hello" => "c'a va latn"
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 47 |
Dict(
"hello" => "cava Latt"
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 47 |
# wrong key type of dictionary
Dict( 1 => 2 )
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 25 |
"wrong type of object"
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 44 |
# error to envoke warning message
Dict(1)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 109 |
Dict(
"T2" => "T2 - en",
"T3" => "T3 - en",
"T4" => "T4 - en",
"T5" => "T5 - en",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 92 |
[
"T4" => "T4 - en_Latn",
"T5" => "T5 - en_Latn",
"T6" => "T6 - en_Latn",
]
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 45 |
Dict(
"T5" => "T5 - en_Latn_US",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 109 |
(
"T3" => "T3 - en_US",
"T5" => "T5 - en_US",
"T6" => "T6 - en_US",
"T7" => "T7 - en_US",
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 36 |
Dict(
"hello" => "cava FR"
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 40 | Dict(
"hello" => "c'a va latn"
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 47 |
Dict(
"hello" => "cava Latt"
)
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 404 | module ResourceBundles
export ResourceBundles
export ResourceBundle, resource_bundle, @resource_bundle
export LocaleId, LC
export @tr_str, string_to_key
include("types.jl")
include("constants.jl")
include("locale_iso_data.jl")
include("resource_bundle.jl")
include("localetrans.jl")
include("locale.jl")
include("string.jl")
include("poreader.jl")
include("clocale.jl")
end # module ResourceBundles
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 9823 |
module CLocales
using ResourceBundles
using ResourceBundles.LocaleIdTranslations
using ResourceBundles.LC
import ResourceBundles: LocaleId, S0, locale, CLocaleType
export current_locale, newlocale, duplocale, freelocale, nl_langinfo, clocale_id
export NlItem, category, offset, typ
export strcoll, localize_isless
export LC_GLOBAL_LOCALE
"""
newlocale(cat::LC.CategorySet, loc::LocaleId[, base::CLocaleType])::CLocaleType
Return a pointer to an opaque locale-object of glibc.
Modifies and invalidate the previously returned `base`.
`categories` may be on or a tuple of symbols `:CTYPE, :NUMERIC, :TIME, :COLLATE, :MONETARY,
:MESSAGES, :ALL, :PAPER, :NAME, :ADDRESS, :TELEPHONE, :MEASUREMENT, :IDENTIFICATION`.
The locale id is converted to a string of a locale name in POSIX-form.
This name must exist in the output of `locale -a` on a system using glibc.
If no such object exists, return `Ptr{Nothing}(0)`.
"""
newlocale(cat::CategorySet, loc::LocaleId) = newlocale(cat, loc, CL0)
function newlocale(cat::CategorySet, loc::LocaleId, base::CLocaleType)
cloc = loc_to_cloc(loc)
newlocale_c(LC.mask(cat), cloc, base)
end
"""
current_clocale()
Return the task-specific current glibc-locale.
Any call to `set_locale!` or `newlocale` invalidates the returned pointer.
"""
function current_clocale()
locale().cloc
end
"""
strcoll(a::AbstractString, b::AbstractString[, loc::LocaleId]) -> -1, 0, 1
Compare two strings a and b using the locale specified by `loc` or the default-locale
for category `:MESSAGES`.
Return `a < b ? -1 : a > b ? 1 : 0`.
"""
strcoll(a::AbstractString, b::AbstractString) = strcoll_c(a, b, current_clocale())
function strcoll(a::AbstractString, b::AbstractString, loc::LocaleId)
ploc = newlocale(LC.ALL, loc)
if ploc != CL0
res = strcoll_c(a, b, ploc)
freelocale(ploc)
res
else
error("no posix locale found for $loc")
end
end
"""
localized_isless([loc::LocaleId])
Return isless function comparing two strings accoding to locale specific collation rules.
If loc is not specified, use category `COLLATE` of current locale.
"""
localized_isless() = (a::AbstractString, b::AbstractString) -> strcoll(a, b) < 0
localized_isless(loc::LocaleId) = (a::AbstractString, b::AbstractString) -> strcoll(a, b, loc) < 0
"""
Mask composed of output-type, category, and offset
"""
struct NlItem
mask::Cint
end
"""
nl_item(cat, offset, typ=0) -> NlItem(::Cint)
Create an NlItem object, which wraps Cint mask.
Result is:
typ == 0: char*
typ == 1: int of same size as pointer
typ == 2: *uint8
"""
function nl_item(cat::Category, offset::Integer, typ::Integer=0)
NlItem(Cint(cat.id & 0x00fff)<<16 + Cint(offset) & 0xffff + Cint(typ)<<28)
end
category(nli::NlItem) = LC.ALL_CATS[((nli.mask>>16) & 0x0fff)+1]
offset(nli::NlItem) = Int(nli.mask & 0xffff)
typ(nli::NlItem) = Int((nli.mask>>>28) & 0xffff)
nl_cmask(cat::NlItem) = cat.mask & Cint(0x0ffffff)
nl_ctype(cat::NlItem) = Int(cat.mask>>>28)
"""
nl_langinfo(cat::NlItem[, loc::CLocaleType] )
-> string value | integer value
Provide information about the locale as stored in the glibc implementation.
"""
function nl_langinfo(cat::NlItem, loc::CLocaleType=current_clocale())
res = nl_langinfo_c(nl_cmask(cat), loc)
nl_convert(Val(nl_ctype(cat)), res)
end
const PTYPE = sizeof(Ptr) == 8 ? Int64 : Int32
const PU0 = Ptr{UInt8}(0)
nl_convert(::Val{0}, res::Ptr{UInt8}) = res === PU0 ? "" : unsafe_string(res)
nl_convert(::Val{1}, res::Ptr{UInt8}) = Int(Base.bitcast(PTYPE, res))
nl_convert(::Val{2}, res::Ptr{UInt8}) = res === PU0 ? 0 : Int(unsafe_wrap(Array, res, 1)[1])
err_day(i::Integer) = throw(ArgumentError("day of week ($i) not between 1 and 7"))
err_month(i::Integer) = throw(ArgumentError("month number ($i) not between 1 and 12"))
"""
clocale_id(category[, cloc::CLocaleType])
Return the name string of a clocale or current clocale.
"""
clocale_id(cat::Category, loc::CLocaleType) = nl_langinfo(nl_item(cat, -1), loc)
clocale_id(cat::Category) = nl_langinfo(nl_item(cat, -1), current_clocale())
include("libc.jl")
## Interface constants derived from /usr/include/langinfo.h
const CTYPE_CODESET = nl_item(LC.CTYPE, 14)
const NUM_LC_CTYPE = 86
const RADIXCHAR = nl_item(LC.NUMERIC, 0)
const THOUSEP = nl_item(LC.NUMERIC, 1)
const THOUSANDS_SEP = nl_item(LC.NUMERIC, 1)
const GROUPING = nl_item(LC.NUMERIC, 2, 2)
const NUMERIC_CODESET = nl_item(LC.NUMERIC, 5)
const NUM_LC_NUMERIC = 6
ABDAY(i::Integer) = 1 <= i <= 7 ? nl_item(LC.TIME, i-1) : err_day(i)
DAY(i::Integer) = 1 <= i <= 7 ? nl_item(LC.TIME, i+6) : err_day(i)
ABMON(i::Integer) = 1 <= i <= 12 ? nl_item(LC.TIME, 13+i) : err_month(i)
MON(i::Integer) = 1 <= i <= 12 ? nl_item(LC.TIME, 25+i) : err_month(i)
const AM_STR = nl_item(LC.TIME, 38)
const PM_STR = nl_item(LC.TIME, 39)
const D_T_FMT = nl_item(LC.TIME, 40)
const D_FMT = nl_item(LC.TIME, 41)
const T_FMT = nl_item(LC.TIME, 42)
const T_FMT_AMPM = nl_item(LC.TIME, 43)
const ERA = nl_item(LC.TIME, 44)
const ERA_YEAR = nl_item(LC.TIME, 45)
const ERA_D_FMT = nl_item(LC.TIME, 46)
const ALT_DIGITS = nl_item(LC.TIME, 47)
const ERA_D_T_FMT = nl_item(LC.TIME, 48)
const ERA_T_FMT = nl_item(LC.TIME, 49)
const NUM_ERA_ENTRIES = nl_item(LC.TIME, 50, 1)
const WEEK_NDAYS = nl_item(LC.TIME, 101, 2)
const WEEK_1STDAY = nl_item(LC.TIME, 102, 1)
const WEEK_1STWEEK = nl_item(LC.TIME, 103, 2)
const FIRST_WEEKDAY = nl_item(LC.TIME, 104, 2)
const FIRST_WORKDAY = nl_item(LC.TIME, 105, 2)
const CAL_DIRECTION = nl_item(LC.TIME, 106, 2)
const TIMEZONE = nl_item(LC.TIME, 107)
const DATE_FMT = nl_item(LC.TIME, 108)
const TIME_CODESET = nl_item(LC.TIME, 110)
const NUM_LC_TIME = 111
const COLLATE_CODESET = nl_item(LC.COLLATE, 18)
const NUM_LC_COLLATE = 19
const YESEXPR = nl_item(LC.MESSAGES, 0)
const NOEXPR = nl_item(LC.MESSAGES, 1)
const YESSTR = nl_item(LC.MESSAGES, 2)
const NOSTR = nl_item(LC.MESSAGES, 3)
const MESSAGES_CODESET = nl_item(LC.MESSAGES, 4)
const NUM_LC_MESSAGES = 5
const INT_CURR_SYMBOL = nl_item(LC.MONETARY, 0)
const CURRENCY_SYMBOL = nl_item(LC.MONETARY, 1)
const MON_DECIMAL_POINT = nl_item(LC.MONETARY, 2)
const MON_THOUSANDS_SEP = nl_item(LC.MONETARY, 3)
const MON_GROUPING = nl_item(LC.MONETARY, 4, 2)
const POSITIVE_SIGN = nl_item(LC.MONETARY, 5)
const NEGATIVE_SIGN = nl_item(LC.MONETARY, 6)
const INT_FRAC_DIGITS = nl_item(LC.MONETARY, 7, 2)
const FRAC_DIGITS = nl_item(LC.MONETARY, 8, 2)
const P_CS_PRECEDES = nl_item(LC.MONETARY, 9, 2)
const P_SEP_BY_SPACE = nl_item(LC.MONETARY, 10, 2)
const N_CS_PRECEDES = nl_item(LC.MONETARY, 11, 2)
const N_SEP_BY_SPACE = nl_item(LC.MONETARY, 12, 2)
const P_SIGN_POSN = nl_item(LC.MONETARY, 13, 2)
const N_SIGN_POSN = nl_item(LC.MONETARY, 14, 2)
const CRNCYSTR = nl_item(LC.MONETARY, 15)
const INT_P_CS_PRECEDES = nl_item(LC.MONETARY, 16, 2)
const INT_P_SEP_BY_SPACE = nl_item(LC.MONETARY, 17, 2)
const INT_N_CS_PRECEDES = nl_item(LC.MONETARY, 18, 2)
const INT_N_SEP_BY_SPACE = nl_item(LC.MONETARY, 19, 2)
const INT_P_SIGN_POSN = nl_item(LC.MONETARY, 20, 2)
const INT_N_SIGN_POSN = nl_item(LC.MONETARY, 21, 2)
const MONETARY_CODESET = nl_item(LC.MONETARY, 45)
const NUM_LC_MONETARY = 46
const PAPER_HEIGHT = nl_item(LC.PAPER, 0, 1)
const PAPER_WIDTH = nl_item(LC.PAPER, 1, 1)
const PAPER_CODESET = nl_item(LC.PAPER, 2)
const NUM_LC_PAPER = 3
const NAME_FMT = nl_item(LC.NAME, 0)
const NAME_GEN = nl_item(LC.NAME, 1)
const NAME_MR = nl_item(LC.NAME, 2)
const NAME_MRS = nl_item(LC.NAME, 3)
const NAME_MISS = nl_item(LC.NAME, 4)
const NAME_MS = nl_item(LC.NAME, 5)
const NAME_CODESET = nl_item(LC.NAME, 6)
const NUM_LC_NAME = 7
const ADDRESS_POSTAL_FMT = nl_item(LC.ADDRESS, 0)
const ADDRESS_COUNTRY_NAME = nl_item(LC.ADDRESS, 1)
const ADDRESS_COUNTRY_POST = nl_item(LC.ADDRESS, 2)
const ADDRESS_COUNTRY_AB2 = nl_item(LC.ADDRESS, 3)
const ADDRESS_COUNTRY_AB3 = nl_item(LC.ADDRESS, 4)
const ADDRESS_COUNTRY_CAR = nl_item(LC.ADDRESS, 5)
const ADDRESS_COUNTRY_NUM = nl_item(LC.ADDRESS, 6, 1)
const ADDRESS_COUNTRY_ISBN = nl_item(LC.ADDRESS, 7)
const ADDRESS_LANG_NAME = nl_item(LC.ADDRESS, 8)
const ADDRESS_LANG_AB = nl_item(LC.ADDRESS, 9)
const ADDRESS_LANG_LIB = nl_item(LC.ADDRESS, 10)
const ADDRESS_LANG_TERM = nl_item(LC.ADDRESS, 11)
const ADDRESS_CODESET = nl_item(LC.ADDRESS, 12)
const NUM_LC_ADDRESS = 13
const TELEPHONE_TEL_INT_FMT = nl_item(LC.TELEPHONE, 0)
const TELEPHONE_TEL_DOM_FMT = nl_item(LC.TELEPHONE, 1)
const TELEPHONE_INT_SELECT = nl_item(LC.TELEPHONE, 2)
const TELEPHONE_INT_PREFIX = nl_item(LC.TELEPHONE, 3)
const TELEPHONE_CODESET = nl_item(LC.TELEPHONE, 4)
const NUM_LC_TELEPHONE = 5
const MEASUREMENT = nl_item(LC.MEASUREMENT, 0, 2)
const MEASUREMENT_CODESET = nl_item(LC.MEASUREMENT, 1)
const NUM_LC_MEASUREMENT = 2
const IDENTIFICATION_TITLE = nl_item(LC.IDENTIFICATION, 0)
const IDENTIFICATION_SOURCE = nl_item(LC.IDENTIFICATION, 1)
const IDENTIFICATION_ADDRESS = nl_item(LC.IDENTIFICATION, 2)
const IDENTIFICATION_CONTACT = nl_item(LC.IDENTIFICATION, 3)
const IDENTIFICATION_EMAIL = nl_item(LC.IDENTIFICATION, 4)
const IDENTIFICATION_TEL = nl_item(LC.IDENTIFICATION, 5)
const IDENTIFICATION_FAX = nl_item(LC.IDENTIFICATION, 6)
const IDENTIFICATION_LANGUAGE = nl_item(LC.IDENTIFICATION, 7)
const IDENTIFICATION_TERRITORY = nl_item(LC.IDENTIFICATION, 8)
const IDENTIFICATION_AUDIENCE = nl_item(LC.IDENTIFICATION, 9)
const IDENTIFICATION_APPLICATION = nl_item(LC.IDENTIFICATION, 10)
const IDENTIFICATION_ABBREVIATION = nl_item(LC.IDENTIFICATION, 11)
const IDENTIFICATION_REVISION = nl_item(LC.IDENTIFICATION, 12)
const IDENTIFICATION_DATE = nl_item(LC.IDENTIFICATION, 13)
const IDENTIFICATION_CATEGORY = nl_item(LC.IDENTIFICATION, 14)
const IDENTIFICATION_CODESET = nl_item(LC.IDENTIFICATION, 15)
const NUM_LC_IDENTIFICATION = 16
LC_GLOBAL_LOCALE = CLocaleType(-1)
CL0 = CLocaleType(0)
end # module
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 406 |
module Constants
export EMPTYV, EMPTYD, EMPTY_VECTOR, S0
export ALL_CATEGORIES
import ResourceBundles: ExtensionDict
const EMPTYV = String[]
const EMPTYD = ExtensionDict()
const S0 = Symbol("")
const EMPTY_VECTOR = Symbol[]
const ALL_CATEGORIES = [ :CTYPE, :NUMERIC, :TIME, :COLLATE, :MONETARY, :MESSAGES,
:PAPER, :NAME, :ADDRESS, :TELEPHONE, :MEASUREMENT, :IDENTIFICATION ]
end
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 1716 |
### accessing libc functions (XOPEN_SOURCE >= 700, POSIX_C_SOURCE >= 200809L glibc>=2.24)
if Sys.isunix() && get(Base.ENV, "NO_CLOCALE", "") != "1"
function newlocale_c(mask::Cint, clocale::AbstractString, base::CLocaleType)
ccall(:newlocale, CLocaleType, (Cint, Cstring, CLocaleType), mask, clocale, base)
end
function duplocale(ploc::CLocaleType)
ccall(:duplocale, CLocaleType, (CLocaleType,), ploc)
end
function freelocale(ploc::CLocaleType)
ccall(:freelocale, Nothing, (CLocaleType,), ploc)
end
function uselocale(newloc::CLocaleType)
ccall(:uselocale, CLocaleType, (CLocaleType,), newloc)
end
function strcoll_c(s1::AbstractString, s2::AbstractString, ploc::CLocaleType)
res = 0
if ploc == CL0
ploc = current_clocale()
res = ccall(:strcoll_l, Cint, (Cstring, Cstring, CLocaleType), s1, s2, ploc)
freelocale(ploc)
else
res = ccall(:strcoll_l, Cint, (Cstring, Cstring, CLocaleType), s1, s2, ploc)
end
Int(res)
end
function nl_langinfo_c(nlitem::Cint, ploc::CLocaleType)
ccall(:nl_langinfo_l, Ptr{UInt8}, (Cint, CLocaleType), nlitem, ploc)
end
else # for the non case provide dummy methods
newlocale_c(mask::Cint, clocale::AbstractString, base::CLocaleType) = CL0
duplocale(ploc::CLocaleType) = CL0
freelocale(ploc::CLocaleType) = nothing
uselocale(newloc::CLocaleType) = CL0
function strcoll_c(s1::AbstractString, s2::AbstractString, ploc::CLocaleType)
s1 == s2 ? 0 : s1 < s2 ? -1 : 1
end
nl_langinfo_c(nlitem::Cint, ploc::CLocaleType) = Ptr{UInt8}(0)
end
#################################
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 13562 |
using .Constants
using .LocaleIdTranslations
using .LC
export LocaleId, Locales, default_locale, locale_id, locale, set_locale!
import Base: ==, hash
"""
LocaleId(languagetag::String))
LocaleId(lang, region)
LocaleId(lang, script, region)
LocaleId(lang, script, region, variant)
LocaleId("") -> DEFAULT
LocaleId() -> BOTTOM
Return `LocaleId` object from cache or create new one and register in cache.
"""
LocaleId() = BOTTOM
LocaleId(langtag::AS) = langtag == "" ? DEFAULT : create_locid(splitlangtag(langtag)...)
LocaleId(lang::AS, region::AS) = create_locid(lang, EMPTYV, "", region, EMPTYV, nothing)
LocaleId(lang::AS, script::AS, region::AS) = create_locid(lang, EMPTYV, script, region, EMPTYV, nothing)
LocaleId(lang::AS, script::AS, region::AS, variant::AS) = create_locid(lang, EMPTYV, script, region, [variant], nothing)
# utilities
# create instance and register in global cache.
function create_locid(language::AS, extlang::Vector{String}, script::AS, region::AS, variant::Vector{String}, extension::Union{ExtensionDict,Nothing})
lang = check_language(language, extlang)
scri = check_script(titlecase(script))
regi = check_region(uppercase(region))
vari = check_variant(variant)
if lang == S0
lex = extension == nothing ? 0 : length(extension)
if !(scri == S0 && regi == S0 && length(vari) == 0 &&
(lex == 1 && first(keys(extension)) == 'x' || lex == 0 ) )
throw(ArgumentError("missing language prefix"))
end
end
key = tuple(lang, scri, regi, vari, extension)
try
lock(CACHE_LOCK)
get!(CACHE, key) do
LocaleId(key...)
end
finally
unlock(CACHE_LOCK)
end
end
function check_language(x::AS, extlang::Vector{String})
is_language(x) || length(x) == 0 || throw(ArgumentError("no language prefix '$x'"))
x = get(OLD_TO_NEW_LANG, x, x)
len = length(extlang)
if length(x) <= 3
len <= 1 || throw(ArgumentError("only one language extension allowed '$x$SEP2$(join(extlang, SEP2))'"))
if len >= 1
x = extlang[1]
end
if length(x) == 3
x = LANGUAGE3_DICT[x] # replace 3-char code by preferred 2-char code
end
else
len == 0 || throw(ArgumentError("no language exensions allowed '$x$SEP2$(join(extlang, SEP2))'"))
end
Symbol(x)
end
function is_language(x::AS)
len = length(x)
(2 <= len <= 8 && is_alpha(x)) || len == 1 && x == "C"
end
function is_langext(x::AS)
len = length(x)
len == 3 && is_alpha(x)
end
function check_script(x::AS)
is_script(x) || length(x) == 0 || throw(ArgumentError("no script '$x'"))
Symbol(x)
end
function is_script(x::AS)
len = length(x)
len == 4 && is_alpha(x)
end
function check_region(x::AS)
is_region(x) || length(x) == 0 || throw(ArgumentError("no region '$x'"))
Symbol(x)
end
function is_region(x::AS)
len = length(x)
( len == 2 && is_alpha(x) ) || ( len == 3 && is_digit(x) )
end
function check_variant(x::Vector{String})
all(is_variant, x) || throw(ArgumentError("no variants '$(join(x, SEP2))'"))
Symbol.(x)
end
function is_variant(x::AS)
len = length(x)
is_alnum(x) && ( ( 4 <= len <= 8 && isdigit(x[1]) ) || ( 5 <= len <= 8 ))
end
function is_single(x::AS)
length(x) == 1 && is_alpha(x)
end
"""
Parse language tag and convert to Symbols and collections of Symbols.
"""
function splitlangtag(x::AS)
is_alnumsep(x) || throw(ArgumentError("language tag contains invalid characters: '$x'"))
x = cloc_to_loc(x) # handle and replace '.' and '@'.
x = replace(x, SEP => SEP2) # normalize input
x = get(GRANDFATHERED, x, x) # replace some old-fashioned language tags
token = split(x, SEP2, keepempty=true)
lang = ""
langex = String[]
scri = ""
regi = ""
vari = String[]
exte = nothing
langlen = 0
k = 1
n = length(token)
if k <= n && is_language(token[k])
lang = token[k]
langlen = length(lang)
k += 1
end
while k <= n && 2 <= langlen <= 3 && is_langext(token[k])
push!(langex, token[k])
k += 1
end
if k <= n && is_script(token[k])
scri = token[k]
k += 1
end
while k <= n && is_region(token[k])
regi = token[k]
k += 1
end
while k <= n && is_variant(token[k])
push!(vari, token[k])
k += 1
end
while k <= n && is_single(token[k])
sing = token[k][1]
if exte == nothing
exte = ExtensionDict()
end
if haskey(exte, sing)
throw(ArgumentError("multiple occurrence of singleton '$sing'"))
end
m = sing == 'x' ? 1 : 2
k += 1
ext = Symbol[]
while k <= n && m <= length(token[k]) <= 8
push!(ext, Symbol(token[k]))
k += 1
end
exte[sing] = ext
end
k > n || x == "" || throw(ArgumentError("no language tag: '$x' after $(k-1)"))
length(langex) <= 3 || throw(ArgumentError("too many language extensions '$x'"))
lang, langex, scri, regi, vari, exte
end
# character properties for all characters in string
is_alpha(x::AS) = all(isletter, x)
is_digit(x::AS) = all(isdigit, x)
is_alnum(x::AS) = all(is_alnum, x)
is_alnumsep(x::AS) = all(c->isascii(c) && ( is_alnum(c) || c in "-_.@" ), x)
# equality
function ==(x::LocaleId, y::LocaleId)
x === y && return true
x.language == y.language &&
x.script == y.script &&
x.region == y.region &&
x.variants == y.variants &&
x.extensions == y.extensions
end
flat(lang::Symbol) = lang == :C ? S0 : lang
function hash(x::LocaleId, h::UInt)
hash(x.extensions, hash(x.variants, hash(x.region, hash(x.script, hash(x.language, h)))))
end
function Base.issubset(x::LocaleId, y::LocaleId)
( x == y || x == BOTTOM || y == ROOT ) && return true
y == BOTTOM && return false
issublang(x.language, y.language) &&
issubscript(x.script, y.script) &&
issubregion(x.region, y.region) &&
issubvar(x.variants, y.variants) &&
issubext(x.extensions, y.extensions)
end
issublang(x::Symbol, y::Symbol) = startswith(string(x), string(y))
issubscript(x::Symbol, y::Symbol) = startswith(string(x), string(y))
issubregion(x::Symbol, y::Symbol) = startswith(string(x), string(y))
issubvar(x::Vector{Symbol}, y::Vector{Symbol}) = issubset(y, x)
function issubext(x::ExtensionDict, y::ExtensionDict)
ky = keys(y)
issubset(ky, keys(x)) &&
all(k-> issubset(y[k], x[k]), ky)
end
issubext(x::Nothing, y::ExtensionDict) = false
issubext(x, y::Nothing) = true
Base.isless(x::LocaleId, y::LocaleId) = issubset(x, y) || (!issubset(y,x) && islexless(x, y))
islexless(x::LocaleId, y::LocaleId) = string(x) < string(y)
"""
less_specific(loc::LocaleId)
Give the next less specific locale id. If loc = ROOT, return ROOT.
"""
function less_specific(loc::LocaleId)
loc == ROOT && return ROOT
if loc.extensions != nothing && !isempty(loc.extensions) > 0
LocaleId(loc.language, loc.script, loc.region, loc.variants, nothing)
elseif length(loc.variants) != 0
LocaleId(loc.language, loc.script, loc.region, Symbol[], nothing)
elseif loc.region != S0
LocaleId(loc.language, loc.script, S0, Symbol[], nothing)
elseif loc.script != S0
LocaleId(loc.language, S0, S0, Symbol[], nothing)
else
ROOT
end
end
function Base.show(io2::IO, x::LocaleId)
ES = Symbol("")
sep = ""
io = IOBuffer()
x.language !== ES && ( print(io, x.language); sep = SEP2 )
x.script != ES && ( print(io, sep, x.script); sep = SEP2 )
x.region != ES && ( print(io, sep, x.region); sep = SEP2 )
for v in x.variants
v != ES && ( print(io, sep, v); sep = SEP2 )
end
ltx(a::Char, b::Char) = ( a != 'x' && a < b ) || b == 'x'
if x.extensions != nothing
for k in sort(collect(keys(x.extensions)), lt=ltx)
print(io, sep, k); sep = SEP2
for v in x.extensions[k]
print(io, sep, v)
end
end
end
out = String(take!(io))
print(io2, out)
end
const CACHE = Dict{Key, LocaleId}()
const CACHE_LOCK = ReentrantLock()
"""
locale_id([gloc::Locale, ]category)
Determine current locale id for given category as stored in locale variable.
If gloc is not given, use task specific locale variable.
Throw exception, if no valid category name.
Valid categories are
:CTYPE, :COLLATE, :MESSAGES, :MONETARY, :NUMERIC, :TIME
"""
locale_id(cat::Category) = locale().locids[cat.id+1]
locale_id(gloc::Locale, cat::Category) = gloc.locids[cat.id+1]
"""
set_locale!([gloc::Locale, ]locale::LocaleId[, category::CategorySet])
Set contents of locale in selected categories.
Missing category or :ALL sets all defined categories to the same locale.
If `gloc` is not given, the current task-specific locale is used.
Throw exception if category is not :ALL or one of the supported categories of `locale`.
"""
set_locale!(loc::LocaleId, cats::CategorySet = LC.ALL) = set_locale!(locale(), loc, cats)
function set_locale!(gloc::Locale, loc::LocaleId, cats::CategorySet = LC.ALL)
cld = gloc.locids
cloc = _newlocale(cats, loc, gloc.cloc)
if cloc != CLocales.CL0 || gloc.cloc == CLocales.CL0
gloc.cloc = cloc
for cat in cats
lloc = loc == DEFAULT ? default_locale(cat) : loc
cld[cat.id+1] = lloc
end
end
cloc != CLocales.CL0 || gloc.cloc == CLocales.CL0
end
function _newlocale(cats::CategorySet, loc::LocaleId, base::CLocaleType)
cloc = CLocales.newlocale(cats, loc, base)
(cloc != CLocales.CL0 || loc == ResourceBundles.ROOT) && return cloc
_newlocale(cats, less_specific(loc), base)
end
"""
default_locale(category)
Determine default locale from posix environment variables:
LANG default if specific category not defined
LC_* specific category
LC_ALL overides all other settings
* may be one of
MESSAGES message catalogs
NUMERIC number formats
MONETARY format of monetary values
TIME date/time formats
"""
function default_locale(category::Category)
LocaleId(localeid_from_env(category))
end
"""
localeid_from_env(category)
Read posix environment variable for category.
"""
function localeid_from_env(category)
s = uppercase(string(category))
if !startswith(s, "LC_")
s = s == "LANG" ? s : "LC_" * s
end
if s == "LC_ALL"
get(ENV, s, "")
else
get2("LC_ALL") do
get2(s) do
get(ENV, "LANG", "C")
end
end
end
end
# treat empty value
function get2(f::Function, k::Any)
v = get(ENV, k, "")
v == "" ? f() : v
end
"""
Locale()
Create and initialize a new `Locale` object.
"""
function Locale()
gloc = Locale(Ptr{Nothing}(0))
for cat in LC.ALL_CATS
set_locale!(gloc, default_locale(cat), cat)
end
gloc
end
"""
locale()
Return task specific locale object.
Create and initialize from environment at first access within a task.
"""
function locale()
tld = task_local_storage()
if !haskey(tld, :CURRENT_LOCALES)
gloc = Locale() # create and fill with default values from ENV
finalizer(finalize_gloc, gloc)
task_local_storage(:CURRENT_LOCALES, gloc)
else
task_local_storage(:CURRENT_LOCALES)
end
end
# finalizer required to free the associated clib object.
function finalize_gloc(gloc::Locale)
if gloc.cloc != Ptr{Nothing}(0)
CLocales.freelocale(gloc.cloc)
end
end
"""
DEFAULT
Useful constant for the default locale identifier. It is used to indicate,
that the actual value for concrete locale category (different form :ALL) has to
be determined from the global environment variables `LC_...` and `LANG`.
"""
const DEFAULT = LocaleId("", "")
"""
ROOT
Useful constant for the root locale. The root locale is the locale whose
language is "C", country, and variant are empty ("") strings. This is regarded
as the base locale of all locales, and is used as the language/country
neutral locale for the locale sensitive operations.
"""
const ROOT = LocaleId("C", "")
const BOTTOM = LocaleId(:Bot, S0, S0, EMPTY_VECTOR, nothing)
"""
Provide a set of commonly used LocaleId with language- and country names
in uppercase. e.g. `FRENCH`, `UK`. See also `names(Locales)`.
"""
module Locales
import ResourceBundles: LocaleId, ROOT, DEFAULT, BOTTOM
export ROOT, DEFAULT, BOTTOM
export ENGLISH, FRENCH, GERMAN, ITALIAN, JAPANESE, KOREAN, CHINESE,
SIMPLIFIED_CHINESE, TRADITIONAL_CHINESE
export FRANCE, GERMANY, ITALY, JAPAN, KOREA, CHINA, TAIWAN, PRC, UK, US, CANADA
# Languages
const ENGLISH = LocaleId("en", "")
const FRENCH = LocaleId("fr", "")
const GERMAN = LocaleId("de", "")
const ITALIAN = LocaleId("it", "")
const JAPANESE = LocaleId("ja", "")
const KOREAN = LocaleId("ko", "")
const CHINESE = LocaleId("zh", "")
const SIMPLIFIED_CHINESE = LocaleId("zh", "CN")
const TRADITIONAL_CHINESE = LocaleId("zh", "TW")
# Countries
const FRANCE = LocaleId("fr", "FR")
const GERMANY = LocaleId("de", "DE")
const ITALY = LocaleId("it", "IT")
const JAPAN = LocaleId("ja", "JP")
const KOREA = LocaleId("ko", "KR")
const PRC = SIMPLIFIED_CHINESE
const CHINA = PRC
const TAIWAN = TRADITIONAL_CHINESE
const UK = LocaleId("en", "GB")
const US = LocaleId("en", "US")
const CANADA = LocaleId("en", "CA")
end # module LocaleTag
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 37772 | """
The 2- and 3-letter ISO 639 language codes.
"""
const IsoLanguageTable =
"aa" * "aar" * # Afar
"ab" * "abk" * # Abkhazian
"ae" * "ave" * # Avestan
"af" * "afr" * # Afrikaans
"ak" * "aka" * # Akan
"am" * "amh" * # Amharic
"an" * "arg" * # Aragonese
"ar" * "ara" * # Arabic
"as" * "asm" * # Assamese
"av" * "ava" * # Avaric
"ay" * "aym" * # Aymara
"az" * "aze" * # Azerbaijani
"ba" * "bak" * # Bashkir
"be" * "bel" * # Belarusian
"bg" * "bul" * # Bulgarian
"bh" * "bih" * # Bihari
"bi" * "bis" * # Bislama
"bm" * "bam" * # Bambara
"bn" * "ben" * # Bengali
"bo" * "bod" * # Tibetan
"br" * "bre" * # Breton
"bs" * "bos" * # Bosnian
"ca" * "cat" * # Catalan
"ce" * "che" * # Chechen
"ch" * "cha" * # Chamorro
"co" * "cos" * # Corsican
"cr" * "cre" * # Cree
"cs" * "ces" * # Czech
"cu" * "chu" * # Church Slavic
"cv" * "chv" * # Chuvash
"cy" * "cym" * # Welsh
"da" * "dan" * # Danish
"de" * "deu" * # German
"dv" * "div" * # Divehi
"dz" * "dzo" * # Dzongkha
"ee" * "ewe" * # Ewe
"el" * "ell" * # Greek
"en" * "eng" * # English
"eo" * "epo" * # Esperanto
"es" * "spa" * # Spanish
"et" * "est" * # Estonian
"eu" * "eus" * # Basque
"fa" * "fas" * # Persian
"ff" * "ful" * # Fulah
"fi" * "fin" * # Finnish
"fj" * "fij" * # Fijian
"fo" * "fao" * # Faroese
"fr" * "fra" * # French
"fy" * "fry" * # Frisian
"ga" * "gle" * # Irish
"gd" * "gla" * # Scottish Gaelic
"gl" * "glg" * # Gallegan
"gn" * "grn" * # Guarani
"gu" * "guj" * # Gujarati
"gv" * "glv" * # Manx
"ha" * "hau" * # Hausa
"he" * "heb" * # Hebrew
"hi" * "hin" * # Hindi
"ho" * "hmo" * # Hiri Motu
"hr" * "hrv" * # Croatian
"ht" * "hat" * # Haitian
"hu" * "hun" * # Hungarian
"hy" * "hye" * # Armenian
"hz" * "her" * # Herero
"ia" * "ina" * # Interlingua
"id" * "ind" * # Indonesian
"ie" * "ile" * # Interlingue
"ig" * "ibo" * # Igbo
"ii" * "iii" * # Sichuan Yi
"ik" * "ipk" * # Inupiaq
"id" * "ind" * # Indonesian (new)
"io" * "ido" * # Ido
"is" * "isl" * # Icelandic
"it" * "ita" * # Italian
"iu" * "iku" * # Inuktitut
"ne" * "heb" * # Hebrew (new)
"ja" * "jpn" * # Japanese
"yi" * "yid" * # Yiddish (new)
"jv" * "jav" * # Javanese
"ka" * "kat" * # Georgian
"kg" * "kon" * # Kongo
"ki" * "kik" * # Kikuyu
"kj" * "kua" * # Kwanyama
"kk" * "kaz" * # Kazakh
"kl" * "kal" * # Greenlandic
"km" * "khm" * # Khmer
"kn" * "kan" * # Kannada
"ko" * "kor" * # Korean
"kr" * "kau" * # Kanuri
"ks" * "kas" * # Kashmiri
"ku" * "kur" * # Kurdish
"kv" * "kom" * # Komi
"kw" * "cor" * # Cornish
"ky" * "kir" * # Kirghiz
"la" * "lat" * # Latin
"lb" * "ltz" * # Luxembourgish
"lg" * "lug" * # Ganda
"li" * "lim" * # Limburgish
"ln" * "lin" * # Lingala
"lo" * "lao" * # Lao
"lt" * "lit" * # Lithuanian
"lu" * "lub" * # Luba-Katanga
"lv" * "lav" * # Latvian
"mg" * "mlg" * # Malagasy
"mh" * "mah" * # Marshallese
"mi" * "mri" * # Maori
"mk" * "mkd" * # Macedonian
"ml" * "mal" * # Malayalam
"mn" * "mon" * # Mongolian
"mo" * "mol" * # Moldavian
"mr" * "mar" * # Marathi
"ms" * "msa" * # Malay
"mt" * "mlt" * # Maltese
"my" * "mya" * # Burmese
"na" * "nau" * # Nauru
"nb" * "nob" * # Norwegian Bokmål
"nd" * "nde" * # North Ndebele
"ne" * "nep" * # Nepali
"ng" * "ndo" * # Ndonga
"nl" * "nld" * # Dutch
"nn" * "nno" * # Norwegian Nynorsk
"no" * "nor" * # Norwegian
"nr" * "nbl" * # South Ndebele
"nv" * "nav" * # Navajo
"ny" * "nya" * # Nyanja
"oc" * "oci" * # Occitan
"oj" * "oji" * # Ojibwa
"om" * "orm" * # Oromo
"or" * "ori" * # Oriya
"os" * "oss" * # Ossetian
"pa" * "pan" * # Panjabi
"pi" * "pli" * # Pali
"pl" * "pol" * # Polish
"ps" * "pus" * # Pushto
"pt" * "por" * # Portuguese
"qu" * "que" * # Quechua
"rm" * "roh" * # Raeto-Romance
"rn" * "run" * # Rundi
"ro" * "ron" * # Romanian
"ru" * "rus" * # Russian
"rw" * "kin" * # Kinyarwanda
"sa" * "san" * # Sanskrit
"sc" * "srd" * # Sardinian
"sd" * "snd" * # Sindhi
"se" * "sme" * # Northern Sami
"sg" * "sag" * # Sango
"si" * "sin" * # Sinhalese
"sk" * "slk" * # Slovak
"sl" * "slv" * # Slovenian
"sm" * "smo" * # Samoan
"sn" * "sna" * # Shona
"so" * "som" * # Somali
"sq" * "sqi" * # Albanian
"sr" * "srp" * # Serbian
"ss" * "ssw" * # Swati
"st" * "sot" * # Southern Sotho
"su" * "sun" * # Sundanese
"sv" * "swe" * # Swedish
"sw" * "swa" * # Swahili
"ta" * "tam" * # Tamil
"te" * "tel" * # Telugu
"tg" * "tgk" * # Tajik
"th" * "tha" * # Thai
"ti" * "tir" * # Tigrinya
"tk" * "tuk" * # Turkmen
"tl" * "tgl" * # Tagalog
"tn" * "tsn" * # Tswana
"to" * "ton" * # Tonga
"tr" * "tur" * # Turkish
"ts" * "tso" * # Tsonga
"tt" * "tat" * # Tatar
"tw" * "twi" * # Twi
"ty" * "tah" * # Tahitian
"ug" * "uig" * # Uighur
"uk" * "ukr" * # Ukrainian
"ur" * "urd" * # Urdu
"uz" * "uzb" * # Uzbek
"ve" * "ven" * # Venda
"vi" * "vie" * # Vietnamese
"vo" * "vol" * # Volapük
"wa" * "wln" * # Walloon
"wo" * "wol" * # Wolof
"xh" * "xho" * # Xhosa
"yi" * "yid" * # Yiddish
"yo" * "yor" * # Yoruba
"za" * "zha" * # Zhuang
"zh" * "zho" * # Chinese
"zu" * "zul" # Zulu
"""
The 2- and 3-letter ISO 3166 country codes.
"""
const IsoCountryTable =
"AD" * "AND" * # Andorra, Principality of
"AE" * "ARE" * # United Arab Emirates
"AF" * "AFG" * # Afghanistan
"AG" * "ATG" * # Antigua and Barbuda
"AI" * "AIA" * # Anguilla
"AL" * "ALB" * # Albania, People's Socialist Republic of
"AM" * "ARM" * # Armenia
"AN" * "ANT" * # Netherlands Antilles
"AO" * "AGO" * # Angola, Republic of
"AQ" * "ATA" * # Antarctica (the territory South of 60 deg S)
"AR" * "ARG" * # Argentina, Argentine Republic
"AS" * "ASM" * # American Samoa
"AT" * "AUT" * # Austria, Republic of
"AU" * "AUS" * # Australia, Commonwealth of
"AW" * "ABW" * # Aruba
"AX" * "ALA" * # Åland Islands
"AZ" * "AZE" * # Azerbaijan, Republic of
"BA" * "BIH" * # Bosnia and Herzegovina
"BB" * "BRB" * # Barbados
"BD" * "BGD" * # Bangladesh, People's Republic of
"BE" * "BEL" * # Belgium, Kingdom of
"BF" * "BFA" * # Burkina Faso
"BG" * "BGR" * # Bulgaria, People's Republic of
"BH" * "BHR" * # Bahrain, Kingdom of
"BI" * "BDI" * # Burundi, Republic of
"BJ" * "BEN" * # Benin, People's Republic of
"BL" * "BLM" * # Saint Barthélemy
"BM" * "BMU" * # Bermuda
"BN" * "BRN" * # Brunei Darussalam
"BO" * "BOL" * # Bolivia, Republic of
"BQ" * "BES" * # Bonaire, Sint Eustatius and Saba
"BR" * "BRA" * # Brazil, Federative Republic of
"BS" * "BHS" * # Bahamas, Commonwealth of the
"BT" * "BTN" * # Bhutan, Kingdom of
"BV" * "BVT" * # Bouvet Island (Bouvetoya)
"BW" * "BWA" * # Botswana, Republic of
"BY" * "BLR" * # Belarus
"BZ" * "BLZ" * # Belize
"CA" * "CAN" * # Canada
"CC" * "CCK" * # Cocos (Keeling) Islands
"CD" * "COD" * # Congo, Democratic Republic of
"CF" * "CAF" * # Central African Republic
"CG" * "COG" * # Congo, People's Republic of
"CH" * "CHE" * # Switzerland, Swiss Confederation
"CI" * "CIV" * # Cote D'Ivoire, Ivory Coast, Republic of the
"CK" * "COK" * # Cook Islands
"CL" * "CHL" * # Chile, Republic of
"CM" * "CMR" * # Cameroon, United Republic of
"CN" * "CHN" * # China, People's Republic of
"CO" * "COL" * # Colombia, Republic of
"CR" * "CRI" * # Costa Rica, Republic of
"CS" * "SCG" * # Serbia and Montenegro
"CU" * "CUB" * # Cuba, Republic of
"CV" * "CPV" * # Cape Verde, Republic of
"CW" * "CUW" * # Cura\u00e7ao
"CX" * "CXR" * # Christmas Island
"CY" * "CYP" * # Cyprus, Republic of
"CZ" * "CZE" * # Czech Republic
"DE" * "DEU" * # Germany
"DJ" * "DJI" * # Djibouti, Republic of
"DK" * "DNK" * # Denmark, Kingdom of
"DM" * "DMA" * # Dominica, Commonwealth of
"DO" * "DOM" * # Dominican Republic
"DZ" * "DZA" * # Algeria, People's Democratic Republic of
"EC" * "ECU" * # Ecuador, Republic of
"EE" * "EST" * # Estonia
"EG" * "EGY" * # Egypt, Arab Republic of
"EH" * "ESH" * # Western Sahara
"ER" * "ERI" * # Eritrea
"ES" * "ESP" * # Spain, Spanish State
"ET" * "ETH" * # Ethiopia
"FI" * "FIN" * # Finland, Republic of
"FJ" * "FJI" * # Fiji, Republic of the Fiji Islands
"FK" * "FLK" * # Falkland Islands (Malvinas)
"FM" * "FSM" * # Micronesia, Federated States of
"FO" * "FRO" * # Faeroe Islands
"FR" * "FRA" * # France, French Republic
"GA" * "GAB" * # Gabon, Gabonese Republic
"GB" * "GBR" * # United Kingdom of Great Britain & N. Ireland
"GD" * "GRD" * # Grenada
"GE" * "GEO" * # Georgia
"GF" * "GUF" * # French Guiana
"GG" * "GGY" * # Guernsey
"GH" * "GHA" * # Ghana, Republic of
"GI" * "GIB" * # Gibraltar
"GL" * "GRL" * # Greenland
"GM" * "GMB" * # Gambia, Republic of the
"GN" * "GIN" * # Guinea, Revolutionary People's Rep'c of
"GP" * "GLP" * # Guadaloupe
"GQ" * "GNQ" * # Equatorial Guinea, Republic of
"GR" * "GRC" * # Greece, Hellenic Republic
"GS" * "SGS" * # South Georgia and the South Sandwich Islands
"GT" * "GTM" * # Guatemala, Republic of
"GU" * "GUM" * # Guam
"GW" * "GNB" * # Guinea-Bissau, Republic of
"GY" * "GUY" * # Guyana, Republic of
"HK" * "HKG" * # Hong Kong, Special Administrative Region of China
"HM" * "HMD" * # Heard and McDonald Islands
"HN" * "HND" * # Honduras, Republic of
"HR" * "HRV" * # Hrvatska (Croatia)
"HT" * "HTI" * # Haiti, Republic of
"HU" * "HUN" * # Hungary, Hungarian People's Republic
"ID" * "IDN" * # Indonesia, Republic of
"IE" * "IRL" * # Ireland
"IL" * "ISR" * # Israel, State of
"IM" * "IMN" * # Isle of Man
"IN" * "IND" * # India, Republic of
"IO" * "IOT" * # British Indian Ocean Territory (Chagos Archipelago)
"IQ" * "IRQ" * # Iraq, Republic of
"IR" * "IRN" * # Iran, Islamic Republic of
"IS" * "ISL" * # Iceland, Republic of
"IT" * "ITA" * # Italy, Italian Republic
"JE" * "JEY" * # Jersey
"JM" * "JAM" * # Jamaica
"JO" * "JOR" * # Jordan, Hashemite Kingdom of
"JP" * "JPN" * # Japan
"KE" * "KEN" * # Kenya, Republic of
"KG" * "KGZ" * # Kyrgyz Republic
"KH" * "KHM" * # Cambodia, Kingdom of
"KI" * "KIR" * # Kiribati, Republic of
"KM" * "COM" * # Comoros, Union of the
"KN" * "KNA" * # St. Kitts and Nevis
"KP" * "PRK" * # Korea, Democratic People's Republic of
"KR" * "KOR" * # Korea, Republic of
"KW" * "KWT" * # Kuwait, State of
"KY" * "CYM" * # Cayman Islands
"KZ" * "KAZ" * # Kazakhstan, Republic of
"LA" * "LAO" * # Lao People's Democratic Republic
"LB" * "LBN" * # Lebanon, Lebanese Republic
"LC" * "LCA" * # St. Lucia
"LI" * "LIE" * # Liechtenstein, Principality of
"LK" * "LKA" * # Sri Lanka, Democratic Socialist Republic of
"LR" * "LBR" * # Liberia, Republic of
"LS" * "LSO" * # Lesotho, Kingdom of
"LT" * "LTU" * # Lithuania
"LU" * "LUX" * # Luxembourg, Grand Duchy of
"LV" * "LVA" * # Latvia
"LY" * "LBY" * # Libyan Arab Jamahiriya
"MA" * "MAR" * # Morocco, Kingdom of
"MC" * "MCO" * # Monaco, Principality of
"MD" * "MDA" * # Moldova, Republic of
"ME" * "MNE" * # Montenegro, Republic of
"MF" * "MAF" * # Saint Martin
"MG" * "MDG" * # Madagascar, Republic of
"MH" * "MHL" * # Marshall Islands
"MK" * "MKD" * # Macedonia, the former Yugoslav Republic of
"ML" * "MLI" * # Mali, Republic of
"MM" * "MMR" * # Myanmar
"MN" * "MNG" * # Mongolia, Mongolian People's Republic
"MO" * "MAC" * # Macao, Special Administrative Region of China
"MP" * "MNP" * # Northern Mariana Islands
"MQ" * "MTQ" * # Martinique
"MR" * "MRT" * # Mauritania, Islamic Republic of
"MS" * "MSR" * # Montserrat
"MT" * "MLT" * # Malta, Republic of
"MU" * "MUS" * # Mauritius
"MV" * "MDV" * # Maldives, Republic of
"MW" * "MWI" * # Malawi, Republic of
"MX" * "MEX" * # Mexico, United Mexican States
"MY" * "MYS" * # Malaysia
"MZ" * "MOZ" * # Mozambique, People's Republic of
"NA" * "NAM" * # Namibia
"NC" * "NCL" * # New Caledonia
"NE" * "NER" * # Niger, Republic of the
"NF" * "NFK" * # Norfolk Island
"NG" * "NGA" * # Nigeria, Federal Republic of
"NI" * "NIC" * # Nicaragua, Republic of
"NL" * "NLD" * # Netherlands, Kingdom of the
"NO" * "NOR" * # Norway, Kingdom of
"NP" * "NPL" * # Nepal, Kingdom of
"NR" * "NRU" * # Nauru, Republic of
"NU" * "NIU" * # Niue, Republic of
"NZ" * "NZL" * # New Zealand
"OM" * "OMN" * # Oman, Sultanate of
"PA" * "PAN" * # Panama, Republic of
"PE" * "PER" * # Peru, Republic of
"PF" * "PYF" * # French Polynesia
"PG" * "PNG" * # Papua New Guinea
"PH" * "PHL" * # Philippines, Republic of the
"PK" * "PAK" * # Pakistan, Islamic Republic of
"PL" * "POL" * # Poland, Republic of Poland
"PM" * "SPM" * # St. Pierre and Miquelon
"PN" * "PCN" * # Pitcairn Island
"PR" * "PRI" * # Puerto Rico
"PS" * "PSE" * # Palestinian Territory, Occupied
"PT" * "PRT" * # Portugal, Portuguese Republic
"PW" * "PLW" * # Palau
"PY" * "PRY" * # Paraguay, Republic of
"QA" * "QAT" * # Qatar, State of
"RE" * "REU" * # Reunion
"RO" * "ROU" * # Romania, Socialist Republic of
"RS" * "SRB" * # Serbia, Republic of
"RU" * "RUS" * # Russian Federation
"RW" * "RWA" * # Rwanda, Rwandese Republic
"SA" * "SAU" * # Saudi Arabia, Kingdom of
"SB" * "SLB" * # Solomon Islands
"SC" * "SYC" * # Seychelles, Republic of
"SD" * "SDN" * # Sudan, Democratic Republic of the
"SE" * "SWE" * # Sweden, Kingdom of
"SG" * "SGP" * # Singapore, Republic of
"SH" * "SHN" * # St. Helena
"SI" * "SVN" * # Slovenia
"SJ" * "SJM" * # Svalbard & Jan Mayen Islands
"SK" * "SVK" * # Slovakia (Slovak Republic)
"SL" * "SLE" * # Sierra Leone, Republic of
"SM" * "SMR" * # San Marino, Republic of
"SN" * "SEN" * # Senegal, Republic of
"SO" * "SOM" * # Somalia, Somali Republic
"SR" * "SUR" * # Suriname, Republic of
"SS" * "SSD" * # South Sudan
"ST" * "STP" * # Sao Tome and Principe, Democratic Republic of
"SV" * "SLV" * # El Salvador, Republic of
"SX" * "SXM" * # Sint Maarten (Dutch part)
"SY" * "SYR" * # Syrian Arab Republic
"SZ" * "SWZ" * # Swaziland, Kingdom of
"TC" * "TCA" * # Turks and Caicos Islands
"TD" * "TCD" * # Chad, Republic of
"TF" * "ATF" * # French Southern Territories
"TG" * "TGO" * # Togo, Togolese Republic
"TH" * "THA" * # Thailand, Kingdom of
"TJ" * "TJK" * # Tajikistan
"TK" * "TKL" * # Tokelau (Tokelau Islands)
"TL" * "TLS" * # Timor-Leste, Democratic Republic of
"TM" * "TKM" * # Turkmenistan
"TN" * "TUN" * # Tunisia, Republic of
"TO" * "TON" * # Tonga, Kingdom of
"TR" * "TUR" * # Turkey, Republic of
"TT" * "TTO" * # Trinidad and Tobago, Republic of
"TV" * "TUV" * # Tuvalu
"TW" * "TWN" * # Taiwan, Province of China
"TZ" * "TZA" * # Tanzania, United Republic of
"UA" * "UKR" * # Ukraine
"UG" * "UGA" * # Uganda, Republic of
"UM" * "UMI" * # United States Minor Outlying Islands
"US" * "USA" * # United States of America
"UY" * "URY" * # Uruguay, Eastern Republic of
"UZ" * "UZB" * # Uzbekistan
"VA" * "VAT" * # Holy See (Vatican City State)
"VC" * "VCT" * # St. Vincent and the Grenadines
"VE" * "VEN" * # Venezuela, Bolivarian Republic of
"VG" * "VGB" * # British Virgin Islands
"VI" * "VIR" * # US Virgin Islands
"VN" * "VNM" * # Viet Nam, Socialist Republic of
"VU" * "VUT" * # Vanuatu
"WF" * "WLF" * # Wallis and Futuna Islands
"WS" * "WSM" * # Samoa, Independent State of
"YE" * "YEM" * # Yemen
"YT" * "MYT" * # Mayotte
"ZA" * "ZAF" * # South Africa, Republic of
"ZM" * "ZMB" * # Zambia, Republic of
"ZW" * "ZWE" # Zimbabwe
"""
ISO 15924 - Codes for the representation of names of scripts
"""
const IsoScriptTable =
"Adlm" * # Adlam
"Afak" * # Afaka
"Aghb" * # Caucasian Albanian
"Ahom" * # Ahom, Tai Ahom
"Arab" * # Arabic
"Aran" * # Arabic (Nastaliq variant)
"Armi" * # Imperial Aramaic
"Armn" * # Armenian
"Avst" * # Avestan
"Bali" * # Balinese
"Bamu" * # Bamum
"Bass" * # Bassa Vah
"Batk" * # Batak
"Beng" * # Bengali (Bangla)
"Bhks" * # Bhaiksuki
"Blis" * # Blissymbols
"Bopo" * # Bopomofo
"Brah" * # Brahmi
"Brai" * # Braille
"Bugi" * # Buginese
"Buhd" * # Buhid
"Cakm" * # Chakma
"Cans" * # Unified Canadian Aboriginal Syllabics
"Cari" * # Carian
"Cham" * # Cham
"Cher" * # Cherokee
"Cirt" * # Cirth
"Copt" * # Coptic
"Cpmn" * # Cypro-Minoan
"Cprt" * # Cypriot syllabary
"Cyrl" * # Cyrillic
"Cyrs" * # Cyrillic (Old Church Slavonic variant)
"Deva" * # Devanagari (Nagari)
"Dogr" * # Dogra
"Dsrt" * # Deseret (Mormon)
"Dupl" * # Duployan shorthand, Duployan stenography
"Egyd" * # Egyptian demotic
"Egyh" * # Egyptian hieratic
"Egyp" * # Egyptian hieroglyphs
"Elba" * # Elbasan
"Ethi" * # Ethiopic (Geʻez)
"Geok" * # Khutsuri (Asomtavruli and Nuskhuri)
"Geor" * # Georgian (Mkhedruli and Mtavruli)
"Glag" * # Glagolitic
"Gong" * # Gunjala Gondi
"Gonm" * # Masaram Gondi
"Goth" * # Gothic
"Gran" * # Grantha
"Grek" * # Greek
"Gujr" * # Gujarati
"Guru" * # Gurmukhi
"Hanb" * # Han with Bopomofo (alias for Han + Bopomofo)
"Hang" * # Hangul (Hangŭl, Hangeul)
"Hani" * # Han (Hanzi, Kanji, Hanja)
"Hano" * # Hanunoo (Hanunóo)
"Hans" * # Han (Simplified variant)
"Hant" * # Han (Traditional variant)
"Hatr" * # Hatran
"Hebr" * # Hebrew
"Hira" * # Hiragana
"Hluw" * # Anatolian Hieroglyphs (Luwian Hieroglyphs, Hittite Hieroglyphs)
"Hmng" * # Pahawh Hmong
"Hmnp" * # Nyiakeng Puachue Hmong
"Hrkt" * # Japanese syllabaries (alias for Hiragana + Katakana)
"Hung" * # Old Hungarian (Hungarian Runic)
"Inds" * # Indus (Harappan)
"Ital" * # Old Italic (Etruscan, Oscan, etc.)
"Jamo" * # Jamo (alias for Jamo subset of Hangul)
"Java" * # Javanese
"Jpan" * # Japanese (alias for Han + Hiragana + Katakana)
"Jurc" * # Jurchen
"Kali" * # Kayah Li
"Kana" * # Katakana
"Khar" * # Kharoshthi
"Khmr" * # Khmer
"Khoj" * # Khojki
"Kitl" * # Khitan large script
"Kits" * # Khitan small script
"Knda" * # Kannada
"Kore" * # Korean (alias for Hangul + Han)
"Kpel" * # Kpelle
"Kthi" * # Kaithi
"Lana" * # Tai Tham (Lanna)
"Laoo" * # Lao
"Latf" * # Latin (Fraktur variant)
"Latg" * # Latin (Gaelic variant)
"Latn" * # Latin
"Leke" * # Leke
"Lepc" * # Lepcha (Róng)
"Limb" * # Limbu
"Lina" * # Linear A
"Linb" * # Linear B
"Lisu" * # Lisu (Fraser)
"Loma" * # Loma
"Lyci" * # Lycian
"Lydi" * # Lydian
"Mahj" * # Mahajani
"Maka" * # Makasar
"Mand" * # Mandaic, Mandaean
"Mani" * # Manichaean
"Marc" * # Marchen
"Maya" * # Mayan hieroglyphs
"Medf" * # Medefaidrin (Oberi Okaime, Oberi Ɔkaimɛ)
"Mend" * # Mende Kikakui
"Merc" * # Meroitic Cursive
"Mero" * # Meroitic Hieroglyphs
"Mlym" * # Malayalam
"Modi" * # Modi, Moḍī
"Mong" * # Mongolian
"Moon" * # Moon (Moon code, Moon script, Moon type)
"Mroo" * # Mro, Mru
"Mtei" * # Meitei Mayek (Meithei, Meetei)
"Mult" * # Multani
"Mymr" * # Myanmar (Burmese)
"Narb" * # Old North Arabian (Ancient North Arabian)
"Nbat" * # Nabataean
"Newa" * # Newa, Newar, Newari, Nepāla lipi
"Nkdb" * # Naxi Dongba (na²¹ɕi³³ to³³ba²¹, Nakhi Tomba)
"Nkgb" * # Naxi Geba (na²¹ɕi³³ gʌ²¹ba²¹, 'Na-'Khi ²Ggŏ-¹baw, Nakhi Geba)
"Nkoo" * # N’Ko
"Nshu" * # Nüshu
"Ogam" * # Ogham
"Olck" * # Ol Chiki (Ol Cemet’, Ol, Santali)
"Orkh" * # Old Turkic, Orkhon Runic
"Orya" * # Oriya (Odia)
"Osge" * # Osage
"Osma" * # Osmanya
"Palm" * # Palmyrene
"Pauc" * # Pau Cin Hau
"Perm" * # Old Permic
"Phag" * # Phags-pa
"Phli" * # Inscriptional Pahlavi
"Phlp" * # Psalter Pahlavi
"Phlv" * # Book Pahlavi
"Phnx" * # Phoenician
"Plrd" * # Miao (Pollard)
"Piqd" * # Klingon (KLI pIqaD)
"Prti" * # Inscriptional Parthian
"Qaaa" * # Reserved for private use (start)
"Qabx" * # Reserved for private use (end)
"Rjng" * # Rejang (Redjang, Kaganga)
"Roro" * # Rongorongo
"Runr" * # Runic
"Samr" * # Samaritan
"Sara" * # Sarati
"Sarb" * # Old South Arabian
"Saur" * # Saurashtra
"Sgnw" * # SignWriting
"Shaw" * # Shavian (Shaw)
"Shrd" * # Sharada, Śāradā
"Shui" * # Shuishu
"Sidd" * # Siddham, Siddhaṃ, Siddhamātṛkā
"Sind" * # Khudawadi, Sindhi
"Sinh" * # Sinhala
"Sora" * # Sora Sompeng
"Soyo" * # Soyombo
"Sund" * # Sundanese
"Sylo" * # Syloti Nagri
"Syrc" * # Syriac
"Syre" * # Syriac (Estrangelo variant)
"Syrj" * # Syriac (Western variant)
"Syrn" * # Syriac (Eastern variant)
"Tagb" * # Tagbanwa
"Takr" * # Takri, Ṭākrī, Ṭāṅkrī
"Tale" * # Tai Le
"Talu" * # New Tai Lue
"Taml" * # Tamil
"Tang" * # Tangut
"Tavt" * # Tai Viet
"Telu" * # Telugu
"Teng" * # Tengwar
"Tfng" * # Tifinagh (Berber)
"Tglg" * # Tagalog (Baybayin, Alibata)
"Thaa" * # Thaana
"Thai" * # Thai
"Tibt" * # Tibetan
"Tirh" * # Tirhuta
"Ugar" * # Ugaritic
"Vaii" * # Vai
"Visp" * # Visible Speech
"Wara" * # Warang Citi (Varang Kshiti)
"Wcho" * # Wancho
"Wole" * # Woleai
"Xpeo" * # Old Persian
"Xsux" * # Cuneiform, Sumero-Akkadian
"Yiii" * # Yi
"Zanb" * # Zanabazar Square
"Zinh" * # Code for inherited script
"Zmth" * # Mathematical notation
"Zsye" * # Symbols (Emoji variant)
"Zsym" * # Symbols
"Zxxx" * # Code for unwritten documents
"Zyyy" * # Code for undetermined script
"Zzzz" # Code for uncoded script
# convert old registered language tags to replacements
GRANDFATHERED = Dict{String,String}(
# "tag" => "preferred",
"art-lojban" => "jbo",
"cel-gaulish" => "xtg-x-cel-gaulish", # fallback
"en-gb-oed" => "en-gb-x-oed", # fallback
"i-ami" => "ami",
"i-bnn" => "bnn",
"i-default" => "en-x-i-default", # fallback
"i-enochian" => "und-x-i-enochian", # fallback
"i-hak" => "hak",
"i-klingon" => "tlh",
"i-lux" => "lb",
"i-mingo" => "see-x-i-mingo", # fallback
"i-navajo" => "nv",
"i-pwn" => "pwn",
"i-tao" => "tao",
"i-tay" => "tay",
"i-tsu" => "tsu",
"no-bok" => "nb",
"no-nyn" => "nn",
"sgn-be-fr" => "sfb",
"sgn-be-nl" => "vgt",
"sgn-ch-de" => "sgg",
"zh-guoyu" => "cmn",
"zh-hakka" => "hak",
"zh-min" => "nan-x-zh-min", # fallback
"zh-min-nan" => "nan",
"zh-xiang" => "hsn",
)
# convert old language codes to new codes
OLD_TO_NEW_LANG = Dict{String,String}(
# "old"=> "new",
"iw" => "he",
"ji" => "yi",
"in" => "id")
abstract type StringDict{K,L,M} end
struct StringDict32 <: StringDict{2,3,5}
data::String
end
struct StringDict50 <: StringDict{0,4,4}
data::String
end
const LANGUAGE3_DICT = StringDict32(IsoLanguageTable)
const COUNTRY3_DICT = StringDict32(IsoCountryTable)
const SCRIPT_SET = StringDict50(IsoScriptTable)
function Base.getindex(d::StringDict{K,L,M}, x3::Union{T,Symbol}) where {K,L,M,T<:AbstractString}
x = string(x3)
length(x) != L && return isa(x3, Symbol) ? x3 : Symbol(x3)
ix = K
while ix >= 0 && ix % M != K+1
fx = findnext(x, d.data, ix+1)
ix = fx == nothing ? -1 : first(fx)
end
ix > 0 ? Symbol(d.data[ix-K:ix-1]) : isa(x3, Symbol) ? x3 : Symbol(x)
end
Base.keys(d::StringDict{K,L,M}) where {K,L,M} = StringKeyIterator{K,L,M}(d.data)
struct StringKeyIterator{K,L,M}
data::String
end
Base.iterate(d::StringDict{K,L,M}) where {K,L,M} = iterate(d, 0)
function Base.iterate(d::StringDict{K,L,M}, s) where {K,L,M}
s >= length(d.data) && return nothing
K == 0 ? Symbol(d.data[s+1:s+L]) : Symbol(d.data[s+K+1:s+K+L]) => Symbol(d.data[s+1:s+K]), s + M
end
Base.length(d::StringDict{K,L,M}) where {K,L,M} = length(d.data) ÷ M
Base.iterate(it::StringKeyIterator{K,L,M}) where {K,L,M} = iterate(it, 1 + K)
function Base.iterate(it::StringKeyIterator{K,L,M}, s) where {K,L,M}
s > length(it.data) && return nothing
Symbol(it.data[s:s+L-1]), s + M
end
Base.length(it::StringKeyIterator{K,L,M}) where {K,L,M} = length(it.data) ÷ M
Base.in(x, d::StringDict{0,L,M}) where {L,M} = d[x] == Symbol("")
"""
The following translation dictionary was created essentially using the following
code snippet:
``` julia
julia> dict = Dict{String,String}()
Dict{String,String} with 0 entries
julia> function normal(s::AbstractString)
a = split(s, "@")
b = split(a[1], ".")
length(a) <= 1 || a[2] == "euro" ? b[1] : b[1] * "@" * a[2]
end
normal (generic function with 1 method)
julia> for line in eachline("/usr/share/X11/locale/locale.alias")
a = split(lowercase(line), r"[[:space]]+", keep=false)
if length(a) == 2 && !startswith(a[1], "#")
endswith(a[1], ":") && (a[1] = a[1][1:end-1])
a1 = normal(a[1])
a2 = normal(a[2])
if a1 != a2
if !haskey(dict, a1)
dict[a1] = a2
println('"', a1, '"', " => ", '"', a2, '"', ",")
end
end
end
end
```
The codeset specifiers have been removed from the input data.
It is assumed, that the codesset has not been used to encode relevant data.
"""
const POSIX_OLD_TO_NEW = Dict(
"posix" => "c",
"posix-utf2" => "c",
"c_c" => "c",
"c" => "en_us",
"cextend" => "en_us",
"english_united-states" => "c",
"a3" => "az_az",
"a3_az" => "az_az",
"af" => "af_za",
"am" => "am_et",
"ar" => "ar_aa",
"as" => "as_in",
"az" => "az_az",
"be" => "be_by",
"be@latin" => "be_by@latin",
"bg" => "bg_bg",
"be_bg" => "bg_bg",
"br" => "br_fr",
"bs" => "bs_ba",
"ca" => "ca_es",
"cs" => "cs_cz",
"cs_cs" => "cs_cz",
"cz" => "cs_cz",
"cz_cz" => "cs_cz",
"cy" => "cy_gb",
"da" => "da_dk",
"de" => "de_de",
"ger_de" => "de_de",
"ee" => "ee_ee",
"el" => "el_gr",
"en" => "en_us",
"en_uk" => "en_gb",
"eng_gb" => "en_gb",
"en_zw" => "en_zs",
"eo" => "eo_xx",
"es" => "es_es",
"et" => "et_ee",
"eu" => "eu_es",
"fa" => "fa_ir",
"fi" => "fi_fi",
"fo" => "fo_fo",
"fr" => "fr_fr",
"fre_fr" => "fr_fr",
"ga" => "ga_ie",
"gd" => "gd_gb",
"gl" => "gl_es",
"gv" => "gv_gb",
"he" => "he_il",
"hi" => "hi_in",
"hne" => "hne_in",
"hr" => "hr_hr",
"hu" => "hu_hu",
"in" => "id_id",
"in_id" => "id_id",
"is" => "is_is",
"it" => "it_it",
"iu" => "iu_ca",
"iw" => "he_il",
"iw_il" => "he_il",
"ja" => "ja_jp",
"jp_jp" => "ja_jp",
"ka" => "ka_ge",
"kl" => "kl_gl",
"kn" => "kn_in",
"ko" => "ko_kr",
"ks" => "ks_in",
"kw" => "kw_gb",
"ky" => "ky_kg",
"lo" => "lo_la",
"lt" => "lt_lt",
"lv" => "lv_lv",
"mai" => "mai_in",
"mi" => "mi_nz",
"mk" => "mk_mk",
"ml" => "ml_in",
"mr" => "mr_in",
"ms" => "ms_my",
"mt" => "mt_mt",
"nb" => "nb_no",
"nl" => "nl_nl",
"nn" => "nn_no",
"no" => "no_no",
"no_no@bokmal" => "no_no",
"no_no@nynorsk" => "no_no",
"nr" => "nr_za",
"nso" => "nso_za",
"ny" => "ny_no",
"no@nynorsk" => "ny_no",
"nynorsk" => "nn_no",
"oc" => "oc_fr",
"or" => "or_in",
"pa" => "pa_in",
"pd" => "pd_us",
"ph" => "ph_ph",
"pl" => "pl_pl",
"pp" => "pp_an",
"pt" => "pt_pt",
"ro" => "ro_ro",
"ru" => "ru_ru",
"rw" => "rw_rw",
"sd" => "sd_in",
"sd@devanagari" => "sd_in@devanagari",
"sh" => "sr_rs@latin",
"sh_ba@bosnia" => "sr_cs",
"sh_hr" => "hr_hr",
"sh_yu" => "sr_rs@latin",
"si" => "si_lk",
"sk" => "sk_sk",
"sl" => "sl_si",
"sq" => "sq_al",
"sr" => "sr_rs",
"sr_yu" => "sr_rs@latin",
"sr@cyrillic" => "sr_rs",
"sr_yu@cyrillic" => "sr_rs",
"sr@latn" => "sr_cs@latin",
"sr_cs@latn" => "sr_cs@latin",
"sr@latin" => "sr_rs@latin",
"sr_rs@latn" => "sr_rs@latin",
"ss" => "ss_za",
"st" => "st_za",
"sv" => "sv_se",
"ta" => "ta_in",
"te" => "te_in",
"tg" => "tg_tj",
"th" => "th_th",
"tl" => "tl_ph",
"tn" => "tn_za",
"tr" => "tr_tr",
"ts" => "ts_za",
"tt" => "tt_ru",
"uk" => "uk_ua",
"ur" => "ur_in",
"uz" => "uz_uz",
"uz_uz@cyrillic" => "uz_uz",
"ve" => "ve_za",
"vi" => "vi_vn",
"wa" => "wa_be",
"xh" => "xh_za",
"yi" => "yi_us",
"zh_cn" => "zh_tw",
"zu" => "zu_za",
"english_uk" => "en_gb",
"english_us" => "en_us",
"french_france" => "fr_fr",
"german_germany" => "de_de",
"portuguese_brazil" => "pt_br",
"spanish_spain" => "es_es",
"american" => "en_us",
"arabic" => "ar_aa",
"bokmal" => "nb_no",
"bokmål" => "nb_no",
"bulgarian" => "bg_bg",
"c-french" => "fr_ca",
"catalan" => "ca_es",
"chinese-s" => "zh_cn",
"chinese-t" => "zh_tw",
"croatian" => "hr_hr",
"czech" => "cs_cz",
"danish" => "da_dk",
"dansk" => "da_dk",
"deutsch" => "de_de",
"dutch" => "nl_nl",
"eesti" => "et_ee",
"english" => "en_en",
"estonian" => "et_ee",
"finnish" => "fi_fi",
"français" => "fr_fr",
"french" => "fr_fr",
"galego" => "gl_es",
"galician" => "gl_es",
"german" => "de_de",
"greek" => "el_gr",
"hebrew" => "he_il",
"hrvatski" => "hr_hr",
"hungarian" => "hu_hu",
"icelandic" => "is_is",
"italian" => "it_it",
"japanese" => "ja_jp",
"korean" => "ko_kr",
"lithuanian" => "lt_lt",
"norwegian" => "no_no",
"polish" => "pl_pl",
"portuguese" => "pt_pt",
"romanian" => "ro_ro",
"rumanian" => "ro_ro",
"russian" => "ru_ru",
"serbocroatian" => "sr_rs@latin",
"sinhala" => "si_lk",
"slovak" => "sk_sk",
"slovene" => "sl_si",
"slovenian" => "sl_si",
"spanish" => "es_es",
"swedish" => "sv_se",
"turkish" => "tr_tr",
"thai" => "th_th",
"univ" => "en_us",
"universal@ucs4" => "en_us",
"iso_8859_1" => "en_us",
"iso_8859_15" => "en_us",
"iso8859-1" => "en_us",
"iso-8859-1" => "en_us",
"japan" => "ja_jp",
"japanese-euc" => "ja_jp",
)
"""
Extracted from cldr_32.0.1/tools/java/org/unicode/cldr/util/data/Script_Metadata.csv
"""
const SCRIPT_OLD_NEW = Dict(
"Common" => "Zyyy",
"Latin" => "Latn",
"Han" => "Hani",
"Cyrillic" => "Cyrl",
"Hiragana" => "Hira",
"Katakana" => "Kana",
"Thai" => "Thai",
"Arabic" => "Arab",
"Hangul" => "Hang",
"Devanagari" => "Deva",
"Greek" => "Grek",
"Hebrew" => "Hebr",
"Tamil" => "Taml",
"Kannada" => "Knda",
"Georgian" => "Geor",
"Malayalam" => "Mlym",
"Telugu" => "Telu",
"Armenian" => "Armn",
"Myanmar" => "Mymr",
"Gujarati" => "Gujr",
"Bengali" => "Beng",
"Gurmukhi" => "Guru",
"Lao" => "Laoo",
"Inherited" => "Zinh",
"Khmer" => "Khmr",
"Tibetan" => "Tibt",
"Sinhala" => "Sinh",
"Ethiopic" => "Ethi",
"Thaana" => "Thaa",
"Oriya" => "Orya",
"Unknown" => "Zzzz",
"Canadian_Aboriginal" => "Cans",
"Syriac" => "Syrc",
"Bopomofo" => "Bopo",
"Nko" => "Nkoo",
"Cherokee" => "Cher",
"Yi" => "Yiii",
"Samaritan" => "Samr",
"Coptic" => "Copt",
"Mongolian" => "Mong",
"Glagolitic" => "Glag",
"Vai" => "Vaii",
"Balinese" => "Bali",
"Tifinagh" => "Tfng",
"Bamum" => "Bamu",
"Batak" => "Batk",
"Cham" => "Cham",
"Javanese" => "Java",
"Kayah_Li" => "Kali",
"Lepcha" => "Lepc",
"Limbu" => "Limb",
"Lisu" => "Lisu",
"Mandaic" => "Mand",
"Meetei_Mayek" => "Mtei",
"New_Tai_Lue" => "Talu",
"Ol_Chiki" => "Olck",
"Saurashtra" => "Saur",
"Sundanese" => "Sund",
"Syloti_Nagri" => "Sylo",
"Tai_Le" => "Tale",
"Tai_Tham" => "Lana",
"Tai_Viet" => "Tavt",
"Avestan" => "Avst",
"Brahmi" => "Brah",
"Buginese" => "Bugi",
"Buhid" => "Buhd",
"Carian" => "Cari",
"Cuneiform" => "Xsux",
"Cypriot" => "Cprt",
"Deseret" => "Dsrt",
"Egyptian_Hieroglyphs" => "Egyp",
"Gothic" => "Goth",
"Hanunoo" => "Hano",
"Imperial_Aramaic" => "Armi",
"Inscriptional_Pahlavi" => "Phli",
"Inscriptional_Parthian" => "Prti",
"Kaithi" => "Kthi",
"Kharoshthi" => "Khar",
"Linear_B" => "Linb",
"Lycian" => "Lyci",
"Lydian" => "Lydi",
"Ogham" => "Ogam",
"Old_Italic" => "Ital",
"Old_Persian" => "Xpeo",
"Old_South_Arabian" => "Sarb",
"Old_Turkic" => "Orkh",
"Osmanya" => "Osma",
"Phags_Pa" => "Phag",
"Phoenician" => "Phnx",
"Rejang" => "Rjng",
"Runic" => "Runr",
"Shavian" => "Shaw",
"Tagalog" => "Tglg",
"Tagbanwa" => "Tagb",
"Ugaritic" => "Ugar",
"Chakma" => "Cakm",
"Meroitic_Cursive" => "Merc",
"Meroitic_Hieroglyphs" => "Mero",
"Miao" => "Plrd",
"Sharada" => "Shrd",
"Sora_Sompeng" => "Sora",
"Takri" => "Takr",
"Braille" => "Brai",
"Caucasian_Albanian" => "Aghb",
"Bassa_Vah" => "Bass",
"Duployan" => "Dupl",
"Elbasan" => "Elba",
"Grantha" => "Gran",
"Pahawh_Hmong" => "Hmng",
"Khojki" => "Khoj",
"Linear_A" => "Lina",
"Mahajani" => "Mahj",
"Manichaean" => "Mani",
"Mende_Kikakui" => "Mend",
"Modi" => "Modi",
"Mro" => "Mroo",
"Old_North_Arabian" => "Narb",
"Nabataean" => "Nbat",
"Palmyrene" => "Palm",
"Pau_Cin_Hau" => "Pauc",
"Old_Permic" => "Perm",
"Psalter_Pahlavi" => "Phlp",
"Siddham" => "Sidd",
"Khudawadi" => "Sind",
"Tirhuta" => "Tirh",
"Warang_Citi" => "Wara",
"Ahom" => "Ahom",
"Anatolian_Hieroglyphs" => "Hluw",
"Hatran" => "Hatr",
"Multani" => "Mult",
"Old_Hungarian" => "Hung",
"SignWriting" => "Sgnw",
"Adlam" => "Adlm",
"Bhaiksuki" => "Bhks",
"Marchen" => "Marc",
"Osage" => "Osge",
"Tangut" => "Tang",
"Newa" => "Newa",
"Masaram Gondi" => "Gonm",
"Nushu" => "Nshu",
"Soyombo" => "Soyo",
"Zanabazar Square" => "Zanb",
)
"""
Registered variants as found in cldr32.0.1/common/validity/variant.xml
"""
const VARIANTS = Set([
"1606nict", "1694acad", "1901", "1959acad", "1994", "1996",
"abl1943", "akuapem", "alalc97", "aluku", "ao1990", "arevela", "arevmda", "asant",
"baku1926", "balanka", "barla", "basiceng", "bauddha", "biscayan", "biske", "bohoric", "boont",
"colb1945", "cornu",
"dajnko",
"ekavsk", "emodeng",
"fonipa", "fonnapa", "fonupa", "fonxsamp",
"hepburn", "heploc", "hognorsk", "hsistemo",
"ijekavsk", "itihasa",
"jauer", "jyutping",
"kkcor", "kociewie", "kscor",
"laukika", "lipaw", "luna1918",
"metelko", "monoton",
"ndyuka", "nedis", "newfound", "njiva", "nulik",
"osojs", "oxendict",
"pahawh2", "pahawh3", "pahawh4", "pamaka", "petr1708", "pinyin", "polyton", "puter",
"rigik", "rozaj", "rumgr",
"scotland", "scouse", "simple", "solba", "sotav", "spanglis", "surmiran", "sursilv", "sutsilv",
"tarask",
"uccor", "ucrcor", "ulster", "unifon",
"vaidika", "valencia", "vallader",
"wadegile",
"xsistemo",
])
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 5032 | """
transformation between locale identifiers in differnet forms
1. form used by POSIX: <lang>_<region>[.<charset>][@<cextension>]
2. form used by BCP47: <lang>[_<script>][_<region>][-<variant>][-lextensions]
"""
module LocaleIdTranslations
using ResourceBundles
using Unicode
import ResourceBundles: SEP
export cloc_to_loc, loc_to_cloc, all_locales
"""
cloc_to_loc(posix::String) -> unicode-locale-id-string
Posix string has the general form `<lang>[_<country>][.<charset>][@<extension>]`.
We transform this to the following string:
`<lang[_<script>][_country>][_<variant>][-x-posix-<extension>]`.
The `@extension` may be transformed to a <script>, a variant, or a private extension.
The charset is ignored. The extension is optional in input and output.
"""
function cloc_to_loc(cloc::String)
cloc == "" && return cloc
if cloc == "C" || uppercase(cloc) == "POSIX"
return "C"
end
cloc = lowercase(cloc)
m = match(REG_POSIX, cloc)
if m == nothing
return cloc
end
mc = m.captures
lang = mc[1]
reg = nostring(mc[3])
charset = nostring(mc[5])
ext = nostring(mc[7])
script = ""
var = ""
if !isempty(ext)
langext = string(lang, mc[6])
if haskey(EXTENSION_TO_SCRIPT, ext)
script = EXTENSION_TO_SCRIPT[ext]
ext = ""
elseif haskey(LANGEXT_TO_VAR, langext)
var = LANGEXT_TO_VAR[langext]
ext = ""
elseif haskey(LANGEXT_TO_NEW, langext)
lang = LANGEXT_TO_NEW[key]
ext = ""
elseif ext in EXTENSIONS_IGNORE
ext = ""
end
end
io = IOBuffer()
write(io, lang)
isempty(script) || write(io, SEP, script)
isempty(reg) || write(io, SEP, reg)
isempty(var) || write(io, SEP, var)
isempty(ext) || write(io, "-x-posix-", ext)
String(take!(io))
end
nostring(s::AbstractString) = s
nostring(::Nothing) = ""
const REG_POSIX = r"(^[[:alpha:]]+)([_-]([[:alpha:]]+))?(\.([[:alnum:]_-]+))?(@([[:alnum:]]+))?$"
const EXTENSION_TO_SCRIPT = Dict(
"cyrillic" => "Cyrl",
"latin" => "Latn",
"devanagari" => "Deva")
const LANGEXT_TO_VAR = Dict(
"es@valencia" => "valencia"
)
const LANGEXT_TO_NEW = Dict(
"aa@saaho" => "ssy",
"gez@abegede" => "aa")
const EXTENSIONS_IGNORE = ["euro"]
const S0 = Symbol("")
"""
loc_to_cloc(loc::LocaleId) -> POSIX string
Translate from LocaleId to String in POSIX Format.
Comparable with cloc_to_loc.
"""
function loc_to_cloc(loc::LocaleId)
s = string(loc)
( s == "C" || uppercase(s) == "POSIX" ) && return "C"
s == "" && return s
lang = loc.language
reg = loc.region
script = loc.script
# only interested in extensions of the form "-x-posix-<ext>"
extd = loc.extensions === nothing ? Symbol[] : get(loc.extensions, 'x', Symbol[])
ext = length(extd) == 2 && extd[1] == :posix ? extd[2] : S0
pext = get(LANG_TO_EXT, string(lang), "")
allo = all_locales() # in the operating system storage (locale -a)
if reg != S0 # all posix locales have a region
if script != S0
key = string(script)
if haskey(SCRIPT_TO_EXT, key)
pext = SCRIPT_TO_EXT[key]
end
end
if ext != S0 && isempty(pext)
pext = string(ext)
end
su = locale_name(lang, reg, pext)
if findfirst(x -> x == su, allo) != 0
return su
end
su = locale_name(loc.language, reg)
if findfirst(x -> x == su, allo) != 0
return su
else
s = loc.language
end
else
s = loc.language
end
s = string(s)
su = locale_name(s, uppercase(s)) # check the case, when lang and reg are the same
if findfirst( x ->x == su, allo) != 0
return su
end
reg = get(PROBABLE_SUBTAGS, s, "")
if reg != ""
su = locale_name(s, reg)
if findfirst( x ->x == su, allo) != 0
return su
end
end
ix = findfirst(x -> x == s || startswith(x, s * '_'), allo)
return ix != 0 ? allo[ix] : "C"
end
locale_name(lang, reg) = string(lang, '_', reg, UTF8)
locale_name(lang, reg, ext) = isempty(ext) ? locale_name(lang, reg) : string(lang, '_', reg, UTF8, '@', ext)
const PROBABLE_SUBTAGS = Dict("en" => "US", "zh" => "CN", "sv" => "SE")
const SCRIPT_TO_EXT = Dict("Deva" => "devanagari", "Latn" => "latin", "Cyrl" => "cyrillic")
const LANG_TO_EXT = Dict("ssy" => "saaho")
allloc = String[]
function all_locales()
global allloc
if isempty(allloc)
list = String[]
push!(list, "C", "POSIX")
for loc in eachline(`locale -a`)
loca, ext = splitext(loc)
simple = ext == "" && '_' ∉ loca
standard = loca == "C" || loca == "POSIX"
if ( simple || ext == UTF8 ) && !standard
push!(list, loc)
end
end
allloc = list
end
allloc
end
const UTF8 = ".utf8"
end # module
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 9121 | """
Represent one text item consisting of original text, translated texts
"""
mutable struct TranslationItem
id::String
plural::String
context::String
strings::Dict{Int,String}
TranslationItem() = new("", "", "", Dict{Int,String}())
end
function init_ti!(ti::TranslationItem)
ti.id = ""
ti.plural = ""
ti.context = ""
empty!(ti.strings)
end
"""
read_po_file'('f::AbstractString')'
Read a file, which contains text data according to the PO format of gettext
ref: //https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
Format is strictly line separated.
A line staring with '#' is a comment line and ignored.
A line starting with a keyword '(msg.*)' has to be followed by a string, enclosed
in '"' in the same line, optionally followed by string continuations in the
following lines. Those strings are concatenated. Characters '"' and '\\' have
to be escaped by a preceding '\\'. The usual C-escape sequences are honored.
Only keywords 'msgid', 'msgid_plural', 'msgstr', and 'msgstr[.*]' are supported.
The "msgid_plural" is used synonymous to the "msgid". If both entries are present,
two separate key-value pairs are generated, with identical '('typical array')' value.
"""
function read_po_file(file::Union{AbstractString,IO})
in_sequence = false
in_keyword = false
dict = Vector{Pair{String,Union{String,Vector{String}}}}()
buffer = IOBuffer()
keyword = ""
index = 0
ti = TranslationItem()
in_ti = 0
function begin_sequence(str::AbstractString)
truncate(buffer, 0)
write(buffer, str)
in_sequence = true
end
function continue_sequence(str::AbstractString)
in_sequence || error("no continuation string expected")
write(buffer, str)
end
function end_sequence()
str = unescape_string(String(take!(buffer)))
in_sequence = false
in_keyword && end_keyword(str)
end
function begin_keyword(key::AbstractString, ix::Any, str::AbstractString)
in_keyword = true
keyword = key
index = ix != nothing ? Meta.parse(ix) : -1
begin_sequence(str)
end
function end_keyword(line::AbstractString)
in_keyword = false
process_keyword(keyword, index, line)
end
function process_keyword(
key::AbstractString,
index::Int,
text::AbstractString,
)
index == -1 || key == "msgstr" || error("not allowed $key[$index]")
if key == "msgid"
in_ti == 3 && process_translation_item(ti)
in_ti <= 1 || error("unexpected $key '$text'")
in_ti = 2
isempty(ti.id) ||
error("several msgids in line ('$ti.id', '$text')")
ti.id = text
elseif key == "msgstr"
in_ti != 0 || error("unexpected $key '$text'")
in_ti = 3
ti.strings[max(index, 0)] = text
elseif key == "msgid_plural"
in_ti == 2 || error("unexpected $key '$text'")
isempty(ti.plural) ||
error("several msgid_plural in line ('$ti.plural', '$text')")
ti.plural = text
elseif key == "msgctxt"
in_ti == 3 && process_translation_item(ti)
in_ti == 0 || error("unexpected $key '$text'")
in_ti = 1
isempty(ti.context) ||
error("several msgctx in line ('$ti.context', '$text')")
ti.context = text
end
end
function process_translation_item(ti::TranslationItem)
add_translation_item!(dict, ti)
init_ti!(ti)
in_ti = 0
end
for line in eachline(file)
if (m = match(REG_KEYWORD, line)) != nothing
in_sequence && end_sequence()
begin_keyword(m.captures[1], m.captures[3], m.captures[4])
elseif (m = match(REG_STRING, line)) != nothing
continue_sequence(m.captures[1])
end
end
in_sequence && end_sequence()
in_ti == 3 && process_translation_item(ti)
dict
end
"""
read_mo_file(f::AbstractString)
Read a file, which contains text data according to the MO format of gettext.
two separate key-value pairs are generated, with identical '('typical array')' value.
"""
function read_mo_file(f::AbstractString)
MAGIC = 0x950412de # little-endian form
NUL = '\x00' # separates different elements of msgid and msgstr (plural forms)
EOT = '\x04' # separates msgctxt from msgid
dict = Vector{Pair{String,Union{String,Vector{String}}}}()
ti = TranslationItem()
data = open(f, "r") do fp
read(fp)
end
datal = sizeof(data)
datal >= 28 || error("file too short - no MO file format")
d = reinterpret(UInt32, data[1:28])
le_machine = ENDIAN_BOM == 0x04030201
le_file = d[1] == MAGIC
le_file ||
ntoh(d[1]) == MAGIC ||
error("wrong magic number - no MO-file format")
conv = le_file ? ltoh : ntoh
le_machine != le_file && (d = conv.(d))
magic, rev, n, origp, tranp, hsize, hashp = d[1:7]
revma, revmi = rev >> 16, rev & 0xffff
origp, tranp, hashp = origp ÷ 4, tranp ÷ 4, hashp ÷ 4
revma == 0 ||
error("revision id ($revma,$revmi) in MO-file - only supported: (0, x)")
datal >= (tranp + 2n) * 4 || error("file too short - no MO file format")
d = reinterpret(Int32, data[5:(tranp+2n)*4])
le_machine != le_file && (d = conv.(d))
for i = 0:2:2n-1
leno = d[origp+i]
ptro = d[origp+i+1]
lent = d[tranp+i]
ptrt = d[tranp+i+1]
stro = String(data[ptro+1:ptro+leno])
strt = String(data[ptrt+1:ptrt+lent])
ix = firstnn(findfirst(isequal(EOT), stro), 0)
if ix > 0
ti.context = stro[1:prevind(stro, ix)]
stro = stro[nextind(stro, ix):end]
end
ix = firstnn(findfirst(isequal(NUL), stro), 0)
if ix > 0
ti.plural = stro[nextind(stro, ix):end]
stro = stro[1:prevind(stro, ix)]
end
ti.id = stro
strtlist = string.(split(strt, NUL))
ti.strings = Dict(enumerate(strtlist))
add_translation_item!(dict, ti)
init_ti!(ti)
end
dict
end
firstnn(a::Any) = a
firstnn(a::Nothing, b::Any...) = firstnn(b...)
firstnn(a::Any, b::Any...) = a
# add translation item to output vector
function add_translation_item!(dict::Vector, ti::TranslationItem)
val = map(p -> p.second, sort(collect(ti.strings)))
if length(val) == 1 && isempty(ti.plural)
val = val[1]
end
!isempty(ti.id) && push!(dict, skey(ti) => val)
!isempty(ti.plural) && ti.plural != ti.id && push!(dict, pkey(ti) => val)
isempty(ti.id) && isempty(ti.plural) && push!(dict, "" => val)
ti
end
# Format strings with and without context information
key(ctx, id) =
isempty(id) || isempty(ctx) ? id : string(SCONTEXT, ctx, SCONTEXT, id)
skey(ti::TranslationItem) = key(ti.context, ti.id)
pkey(ti::TranslationItem) = key(ti.context, ti.plural)
"""
read_header(string)
Extract plural data (nplurals and function plural(n)) from string.
"""
function read_header(str::AbstractString)
io = IOBuffer(str)
for line in eachline(io)
if (m = match(REG_PLURAL, line)) != nothing
return translate_plural_data(m.captures[1])
end
end
translate_plural_data("")
end
module Sandbox end
# clip output of eval(ex(n)) to interval [0, m)
create_plural(ex::Expr, m) =
n -> max(min(Base.invokelatest(Sandbox.eval(ex), n), m - 1), 0)
# avoid the following error when calling f by invokelatest:
# "MethodError: no method matching (::getfield(ResourceBundles, Symbol("...")))(::Int64)
# The applicable method may be too new: running in world age ~3, while current world is ~4."
# This is maybe an undesirable hack - looking for more elegant work around.
"""
translate_plural_data(string)
Parses a string of form `"nplurals = expr1; plural = expr(n)"`.
`expr1` must be a constant integer expression.
`expr(n) must be an integer arthmetic expression with a variable `n`.
Outputs the evaluation of `Int(expr1)` and of `n::Int -> expr(n)`.
"""
function translate_plural_data(str::AbstractString)
nplurals = 2
plural = n -> n != 0
str = replace(str, ':' => " : ") # surround : by blanks
str = replace(str, '?' => " ? ") # surround ? by blanks
str = replace(str, "/" => "÷") # use Julia integer division for /
top = Meta.parse(str)
isa(top, Expr) || return nplurals, plural
for a in top.args
if isa(a, Expr) && a.head == :(=)
var, ex = a.args
if var == :nplurals
nplurals = Int(Sandbox.eval(ex)) # evaluate right hand side
elseif var == :plural
ex2 = Expr(:(->), :n, ex)
plural = create_plural(ex2, nplurals)
@assert plural(1) == 0 string(ex, " not 0 for n == 1")
end
end
end
nplurals, plural
end
const REG_KEYWORD = r"""^\s*([a-zA-Z_]+)(\[(\d+)\])?\s+"(.*)"\s*$"""
const REG_STRING = r"""^\s*"(.*)"\s*$"""
const REG_COMMENT = r"""^\s*#"""
const REG_PLURAL = r"""^\s*Plural-Forms:(.*)$"""
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 13978 | using Base.Filesystem
using Unicode
using .LC
const LocalePattern = LocaleId
const Pathname = String
struct Resource
file::String
locale::LocaleId
nplurals::Int
plural::Function
dict::Dict{String,<:Any}
end
mutable struct Cache
list::Vector{Pair{LocalePattern,Pathname}}
dict::Dict{LocalePattern,Resource}
end
#function Resource(f::AbstractString, res::Dict{String,T}) where T
# Resource(f, BOTTOM, 1, (n)->0, res)
#end
is_alnum(x::Char) = isletter(x) || isnumeric(x)
struct ResourceBundle
path::Pathname
name::String
cache::Dict{LocaleId,Cache}
lock::ReentrantLock
function ResourceBundle(path::Pathname, name::AbstractString)
( !isempty(name) && all(is_alnum, name) ) ||
throw(ArgumentError("resource names require alphanumeric but is `$name`"))
new(path, string(name), Dict{LocaleId,Cache}(), ReentrantLock())
end
end
function ResourceBundle(mod::Module, name::AbstractString)
ResourceBundle(resource_path(mod, name), name)
end
const Empty = ResourceBundle("", "empty")
const SEP = '-'
const SEP2 = '_'
const JEND = ".jl" # extension of Julia resource file
const PEND = ".po" # extension of PO resource file
const MEND = ".mo" # extension of MO resource file
const RESOURCES = "resources" # name of subdirectory
const JRB = "JULIA_RESOURCE_BASE" # enviroment variable
"""
resource_path(module, name) -> String
Return path name of resource directory for a module containing data for `name`.
If top module is `Main` the path is derived from enviroment `JULIA_RESOURCE_BASE`.
If `Sys.BINDIR/../../stdlib/<module>/resources` is a directory, we assume
the resources of a module in the standard library.
Otherwise the directory `pathof(<module>)/../../resources` is selected; that is
the usual case for user defined modules.
Submodules may have specific resource files. They are located in subdirectories
of the `resources` directory with path names corresponding to submodule name.
example: Module `MyModule.X.Y` can store specific resource files in
`.../MyModule/resources/X/Y`. If for a given name, no resources are found in the
deepest directory, fallback to previous directory happens. In the example, the
resources are searched first in `resources/X/Y`, then in `resources/X`, then in `resources`.
Nevertheless the resources for one name are always taken from only one subdirectory.
"""
function resource_path(mod::Module, name::AbstractString)
mp = module_path(mod)
if mp === nothing
base = get(ENV, JRB, pwd())
else
base = joinpath(mp, "..", "..")
end
path = "."
prefix = normpath(base, RESOURCES)
ms = module_split(mod)
if is_resourcepath(prefix, name)
n = length(ms)
path = prefix
for i = 2:n
prefix = joinpath(prefix, mod2file(ms[i]))
if is_resourcepath(prefix, name)
path = prefix
end
end
end
path
end
function module_path(mod::Module)
mod === nothing && return nothing
pmod = parentmodule(mod)
pmod === mod ? pathof(mod) : module_path(pmod)
end
"""
package_path(mod)
Return installation directory for module `mod`.
"""
function package_path(name)
name = string(name)
path1 = normpath(Sys.BINDIR, "..", "..", "stdlib", name)
path2 = Pkg.dir(name)
is1 = isdir(path1)
is2 = isdir(path2)
is1 && is2 && @warn("module '$name' has same name as stdlib module")
splitdir(is2 ? path2 : is1 ? path1 : name)[1]
end
"""
is_resourcepath(path, name)
Check if directory `path` contains subdirectory `name` or a file `name_*` or `name.jl`.
Path may be relative or absolute. Name may be string or symbol.
"""
function is_resourcepath(path::AbstractString, name::AbstractString)
isdir(path) || return false
isdir(joinpath(path, string(name))) && return true
stp = name * string(SEP2)
function resind(f::AbstractString)
fname, fext = splitext(f)
startswith(f, stp) || ( fname == name && ( fext == JEND || fext == PEND || fext == MEND ) )
end
any(resind, readdir(path))
end
"""
module_split(mod::Module)
Return the list of module names of a module hierarchy.
Example: `Base.Iterators -> [:Main,:Base,:Iterators]`.
"""
function module_split(mod::Module)
fullname(mod)
end
"""
findfiles(bundle, locale) -> Cache
Produce cache object, which contains list of pairs of locale patterns and pathnames of
potential resource file, restricted to the given locale. The file names are all of the form
`absfilename(path, name) * locstring * ".jl"`
where `locstring` is in the form of a locale-pattern, with locale-separators replaced by
characters `_` or `/`.
The list is sorted with most specific locale-pattern first. The list needs not be totally
ordered (with respect to `⊆`, which allows ambiguous
Example: for `LocaleId("de-DE")`, the resource files could be `name_de_DE.jl` or
`name_de/DE.jl` or `name/de_DE.jl` or `name/de/DE.jl`. If more than one of those files exist,
only the first one (in topdown-order of `walkdir`) is used.
"""
function findfiles(bundle::ResourceBundle, loc::LocaleId)
dir = normpath(bundle.path)
name = bundle.name
flist = Dict{LocalePattern,Pathname}() #
prefix = joinpath(dir, name)
np = sizeof(prefix)
if dir != "."
for (root, dirs, files) in walkdir(dir)
for f in files
file = joinpath(root, f)
if startswith(file, prefix)
locpa = locale_pattern(file[nextind(file,np):end])
if locpa != nothing && !haskey(flist, locpa) && loc ⊆ locpa
push!(flist, locpa => file)
end
end
end
end
end
locs = sort(collect(keys(flist)))
Cache(collect(loc => flist[loc] for loc in locs), Dict{LocalePattern,Resource}())
end
# derive locale pattern from file path
function locale_pattern(f::AbstractString)
d, f = splitdir(f)
f, fext = splitext(f)
if isempty(fext) && startswith(f, ".")
f, fext = "", f
end
( fext == JEND || fext == PEND || fext == MEND ) || return nothing
f = isempty(f) ? d : joinpath(d, f)
f = replace(f, Filesystem.path_separator => SEP)
f = replace(f, SEP2 => SEP)
if isempty(f)
LocaleId("C")
elseif f[1] == SEP
LocaleId(f[nextind(f, 1):end])
else
nothing
end
end
"""
load_file(path)
Load file and create an object of type Resource.
The loaded file must contain valid julia code returning a dictionary object of the
requested type, or an array of pairs, which can be used to construct one.
Alternatively, if the value type is `String`, in the case of message resource files,
The file content may be formattet as a gettext po file.
In case of errors, a warning is printed to logging device and `nothing` is returned.
"""
function load_file(f::AbstractString, locpa::LocaleId=BOTTOM)
d = nothing
dict = nothing
_, fext = splitext(f)
if fext == JEND
d = load_file_jl(f)
elseif fext == MEND
d = load_file_mo(f)
elseif fext == PEND
d = load_file_po(f)
else
@warn("invalid extension of file name '$f'")
end
if isa(d, Union{Vector{T},NTuple{N,Pair},T} where {T<:Pair,N})
d = Dict(d)
end
if isa(d, Dict)
el = eltype(d).parameters
if el[1] <: String
dict = d
else
@warn("Wrong type 'Dict{$(el[1]),$(el[2])}' loaded from '$f'")
end
else
@warn("Wrong type '$(typeof(d))' loaded from '$f' is not a dictionary")
end
if dict != nothing
hdr = get(dict, "", "")
nplurals, plural = read_header(hdr)
return Resource(f, locpa, nplurals, plural, dict)
end
nothing
end
function load_file_typed(f::AbstractString, readf::Function)
d = nothing
try
d = readf(f)
@debug("loaded resource file $f")
catch ex
@warn("loading resource file '$f': $ex")
end
d
end
load_file_jl(f::AbstractString) = load_file_typed(f, include)
load_file_po(f::AbstractString) = load_file_typed(f, read_po_file)
load_file_mo(f::AbstractString) = load_file_typed(f, read_mo_file)
import Base.get
"""
get(bundle::ResourceBundle[, locale], key::String [,default]) -> Any
Return value associated with the locale and key.
If the locale is not given, use the ResourceBundles current locale for messages.
If no default value is given, return `nothing`.
"""
function get(bundle::ResourceBundle, loc::LocaleId, key::AbstractString, default=nothing)
resource = get_resource_by_key(bundle, loc, key)
resource != nothing ? get(resource.dict, key, default) : default
end
"""
get_resource_by_key(bundle[, locale], key) -> Resource
Get resource object which contains key. It also provides multiplicity information.
If the key is not found in any resource file, return `nothing`.
"""
function get_resource_by_key(bundle::ResourceBundle, loc::LocaleId, key::AbstractString)
try
lock(bundle.lock)
cache = initcache!(bundle, loc)
flist = cache.list
rlist = Vector()
xloc = LocaleId("")
val = nothing
for (locpa, path) in flist
resource = ensure_resource!(bundle, cache, locpa, path, rlist)
if resource != nothing && haskey(resource.dict, key)
if val == nothing
xloc = locpa
val = resource
else
if xloc ⊆ locpa
break
else
@warn string("Ambiguous key '", key, "' for ", loc, " in patterns ", xloc, " and ", locpa)
end
end
end
end
clean_cache_list(cache, rlist)
val
finally
unlock(bundle.lock)
end
end
# variants using default locale for messages
msg_loc() = locale_id(LC.MESSAGES)
get(bundle::ResourceBundle, key::String, default=nothing) = get(bundle, msg_loc(), key, default)
get_resource_by_key(bundle::ResourceBundle, key::String) = get_resource_by_key(bundle, msg_loc(), key)
import Base.keys
"""
keys(bundle, locale)
keys(bundle)
Return array of all defined keys for a specific locale or all possible locales.
"""
function Base.keys(bundle::ResourceBundle, loc::LocaleId)
try
lock(bundle.lock)
cache = initcache!(bundle, loc)
flist = cache.list
dlist = Vector()
rlist = Vector()
val = nothing
for (locpa, path) in flist
resource = ensure_resource!(bundle, cache, locpa, path, rlist)
if resource != nothing
push!(dlist, keys(resource.dict))
end
end
clean_cache_list(cache, rlist)
if isempty(dlist)
String[]
else
sort!(unique(Iterators.flatten(dlist)))
end
finally
unlock(bundle.lock)
end
end
Base.keys(bundle::ResourceBundle) = keys(bundle, BOTTOM)
#remove unused files from cache list
function clean_cache_list(cache::Cache, rlist::Vector)
if !isempty(rlist)
cache.list = setdiff(cache.list, rlist)
end
end
# select all potential source dictionaries for given locale.
function initcache!(bundle::ResourceBundle, loc::LocaleId)
get!(bundle.cache, loc) do
findfiles(bundle, loc)
end
end
# load all entries from one dictionary file.
function ensure_resource!(bundle::ResourceBundle, cache::Cache, locpa::LocalePattern, path::String, rlist::Vector)
if haskey(cache.dict, locpa)
resource = cache.dict[locpa]
else
resource = get_resource_by_pattern(bundle, locpa)
if resource == nothing
resource = load_file(path, locpa)
end
if resource != nothing
cache.dict[locpa] = resource
else
push!(rlist, locpa)
end
end
resource
end
"""
get_resource_by_pattern(bundle, locale_pattern)
Obtain resource object of a bundle, which is identified by a locale pattern.
That is commonly constructed of the contents of one resource file, that has the
locale pattern as part of its name.
"""
function get_resource_by_pattern(bundle::ResourceBundle, locpa::LocalePattern)
for cache in values(bundle.cache)
if haskey(cache.dict, locpa)
return cache.dict[locpa]
end
end
nothing
end
mod2file(name::Symbol) = string("M-", name)
is_module_specific(mod::Module, path) = is_module_specific(module_split(mod), path)
function is_module_specific(mp::NTuple{N,Symbol}, path::AbstractString) where N
dir, file = splitdir(path)
isrootmod = length(mp) <= 1
isabspath(dir) &&
(( isrootmod && file == RESOURCES ) ||
(!isrootmod && file == mod2file(mp[end]) && is_module_specific(mp[1:end-1], dir) ))
end
const LOCK = ReentrantLock()
function define_resource_variable(mod::Module, varname::Symbol, bundlename::AbstractString)
try
lock(LOCK)
if !isdefined(mod, varname)
path = resource_path(mod, bundlename)
if is_module_specific(mod, path)
mod.eval(:(const $varname = ResourceBundle($mod, $bundlename)))
elseif isabspath(path)
parent = parentmodule(mod)
prev = define_resource_variable(parent, varname, bundlename)
mod.eval(:(const $varname = $parent.$varname))
else
mod.eval(:(const $varname = ResourceBundles.Empty))
end
else
mod.eval(varname)
end
finally
unlock(LOCK)
end
end
"""
resource_bundle(module, name)
@resource_bundle name
Create global variable named `RB_<name>` in module `mod`, which contains corresponding
resource bundle. If the variable preexists, just return it. The macro envocation is
equivalent to calling `resource_bundle(@__MODULE__, name)`.
"""
function resource_bundle(mod::Module, name::AbstractString)
define_resource_variable(mod, Symbol("RB_", name), name)
end
macro resource_bundle(name::AbstractString)
:(resource_bundle($__module__, $name))
end
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 4258 |
"""
Name of resource bundle used for string messages.
"""
const MESSAGES = "messages"
"""
tr"string_with_interpolation"
Return translated string accoring to string database and a default locale.
The interpolated values are embedded into the translated string.
Multiple plural forms are supported. The multiplicity is determined by the primary
interpolation value, which must be an integer.
"""
macro tr_str(p)
src, mod = VERSION < v"0.7-DEV" ?
(LineNumberNode(0), current_module()) : (__source__, __module__)
tr_macro_impl(src, mod, p)
end
"""
string_to_key(text::AbstractString)
Convert text to key. Replace interpolation syntax with standardized interpoleated integers.
Example without explicit primarity:
`string_to_key("text\$var \$(expr) \$(77)") == "text$(1) $(2) $(3)"`
Example with explicit primarity:
`string_to_key("text\$var \$(!(expr)) \$(77)") == "text$(2) $(1) $(3)"`
(The first interpolation annotated with '`!`' gets number 1).
The interpolation must not be a literal string.
"""
string_to_key(p::AbstractString) = _string2ex1(p)[3]
function tr_macro_impl(::LineNumberNode, mod::Module, p::Any)
ex1, arg, s1 = _string2ex1(p)
arg = Expr(:tuple, arg...)
:(eval(translate($s1, $mod, $ex1, $(esc(arg)))))
end
#
function translate(s1::AbstractString, mod::Module, ex1, arg)
mb = resource_bundle(mod, MESSAGES)
resource = get_resource_by_key(mb, s1)
s2 = resource != nothing ? get(resource.dict, s1, s1) : s1
_translate(s1, s2, resource, ex1, arg)
end
# translate in case of single translation text
function _translate(s1::AbstractString, s2::AbstractString, resource, ex1::Any, arg)
ex2, ind2 = _string2ex(s2, arg)
if length(ind2) > 0
m1, m2 = extrema(ind2)
m1 >= 1 && m2 <= length(arg) || return ex1
end
ex2
end
#translate in case of multiple translation texts (plural forms)
function _translate(s1::AbstractString, s2::Vector{S}, resource, ex1::Any, arg) where S<:AbstractString
length(arg) >= 1 || throw(ArgumentError("tr needs at least one argument: '$s1'"))
mp = arg[1]
n = isinteger(mp) ? abs(Int(mp)) : 999 # if arg not integer numerically use plural form
ix = resource != nothing ? resource.plural(n) + 1 : 1
m = length(s2)
ix = ifelse(ix <= m, ix, m)
str = ix > 0 ? s2[ix] : s1 # fall back to key if vector is empty
_translate(s1, str, resource, ex1, arg)
end
# produce modified Expr, list of interpolation arguments, and key string
function _string2ex1(p::AbstractString)
ex = Meta.parse(string(TQ, p, TQ)) # parsing text argument of str_tr
args = isa(ex, Expr) ? ex.args : [ex]
ea = []
i = 1
multi = false
for j in 1:length(args)
a = args[j]
if ! ( a isa String )
if !multi && a isa Expr && a.head == :call && a.args[1] == SPRIME
multi = true
pushfirst!(ea, a.args[2]) # this argument goes to index 1
args[j] = 1
for k = 1:j-1
if args[k] isa Int # previous arguments shift index
args[k] += 1
end
end
i += 1
else
args[j] = i
push!(ea, a)
i += 1
end
end
end
io = IOBuffer()
for j in 1:length(args)
a = args[j]
if a isa String
print(io, a)
else
print(io, "\$(", a, ")")
end
end
ex, ea, String(take!(io))
end
# produce Expr with interpolation arguments replaced, and original list of positions
function _string2ex(p::AbstractString, oldargs)
ex = Meta.parse(string(TQ, p, TQ)) # parsing translated text
args = isa(ex, Expr) ? ex.args : [ex]
i = 0
ea = Int[]
n = oldargs == nothing ? 0 : length(oldargs)
for j in 1:length(args)
a = args[j]
if a isa Int
i += 1
args[j] = 0 < a <= n ? oldargs[a] : a
push!(ea, a)
end
end
ex, ea
end
TQ = "\"\"\"" # three quote characters in a string
SPRIME = :! # multiplicity indicator in tr-string tr"... $(!count) ..."
SCONTEXT = "§" # context separator in tr-string tr"§ctxname§..."
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 3680 |
module LC
export Category, CategorySet
import Base: show, issubset, |, iterate, length
"""
Locale category.
Constants for each of the LC_xxxxxx categories of the GNU locale definition
are provided. The implementation class shall not be visible.
"""
abstract type CategorySet end
abstract type Category <: CategorySet end
struct _CategoryImplementation <: Category
name::Symbol
id::Int8
mask::Cint
_CategoryImplementation(n::Symbol, nr::Integer) = new(n, nr, 1<<nr)
end
const CTYPE = _CategoryImplementation(:CTYPE, 0)
const NUMERIC = _CategoryImplementation(:NUMERIC, 1)
const TIME = _CategoryImplementation(:TIME, 2)
const COLLATE = _CategoryImplementation(:COLLATE, 3)
const MONETARY = _CategoryImplementation(:MONETARY, 4)
const MESSAGES = _CategoryImplementation(:MESSAGES, 5)
const ALL = _CategoryImplementation(:ALL, 6)
const PAPER = _CategoryImplementation(:PAPER, 7)
const NAME = _CategoryImplementation(:NAME, 8)
const ADDRESS = _CategoryImplementation(:ADDRESS, 9)
const TELEPHONE = _CategoryImplementation(:TELEPHONE, 10)
const MEASUREMENT = _CategoryImplementation(:MEASUREMENT, 11)
const IDENTIFICATION = _CategoryImplementation(:IDENTIFICATION, 12)
const ALL_CATS = [CTYPE, NUMERIC, TIME, COLLATE, MONETARY, MESSAGES, ALL,
PAPER, NAME, ADDRESS, TELEPHONE, MEASUREMENT, IDENTIFICATION]
const NUM_CATS = 13
const _MASK_ALL = Cint(1<<6)
const _MASK_SUM = Cint(((1<<NUM_CATS)-1) & ~_MASK_ALL) # bits of all valid categories
struct _CategorySetImplementation <: CategorySet
mask::Cint
_CategorySetImplementation(m::Cint) = new(m & _MASK_ALL == 0 ? m : _MASK_ALL)
end
mask(cat::CategorySet) = cat.mask
show(io::IO, cat::Category) = print(io, string(cat.name))
function show(io::IO, cs::CategorySet)
mcs = mask(cs)
suc = false
for cat in ALL_CATS
if mcs & mask(cat) != 0
suc && print(io, '|')
show(io, cat)
suc = true
end
end
end
function issubset(a::CategorySet,b::CategorySet)
ma, mb = mask(a), mask(b)
( ma | mb == mb ) || (mb & _MASK_ALL != 0)
end
function |(a::CategorySet, b::CategorySet)
ma, mb = mask(a), mask(b)
mab = ma | mb
mab & _MASK_ALL != 0 ? ALL :
mab == ma ? a :
mab == mb ? b :
_CategorySetImplementation(mab)
end
iterate(cat::CategorySet) = iterate(cat, cat === ALL ? _MASK_SUM : cat.mask)
function iterate(cat::CategorySet, s)
s == 0 && return nothing
ix = trailing_zeros(s) + 1
cat = ALL_CATS[ix]
cat, s & ~mask(cat)
end
length(cat::Category) = cat == ALL ? count_ones(_MASK_SUM) : 1
length(cat::CategorySet) = count_ones(mask(cat))
end # module LC
"""
struct LocaleId
Represent a Languange Tag, also known as Locale Identifier as defined by BCP47.
See: https://tools.ietf.org/html/bcp47
"""
struct LocaleId
language::Symbol
script::Symbol
region::Symbol
variants::Vector{Symbol}
extensions::Union{Dict{Char,Vector{Symbol}},Nothing}
end
"""
mutable struct Locale
Keeps a locale identifier for each locale category.
The locale categories are defined like in GNU (see `man 7 locale`).
Parallel to that the libc implementation of locale is kept as a cache.
The latter is maintained by the libc functions `newlocale` / `freelocale`.
"""
mutable struct Locale
locids::Vector{LocaleId}
cloc::Ptr{Nothing}
Locale(ptr::Ptr{Nothing}) = new(fill(LocaleId(""), LC.NUM_CATS), ptr)
end
### unexported types
const CLocaleType = Ptr{Nothing}
const AS = AbstractString
const VariantVector = Vector{Symbol}
const ExtensionDict = Dict{Char,VariantVector}
const Key = Tuple{Symbol, Symbol, Symbol, VariantVector, Union{ExtensionDict,Nothing}}
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 5858 |
using .CLocales
using .LC
set_locale!(LocaleId("C"), LC.ALL)
const cl = locale()
const ALLCAT = collect(LC.ALL)
@test cl != Ptr{Nothing}(0)
@testset "clocale identifiers C for $sym" for sym in ALLCAT
@test clocale_id(sym) == "C"
end
for cat in ALLCAT
ENV[string("LC_", cat)] = ""
end
clocid = "fr_FR.utf8"
ENV["LANG"] = clocid
ENV["LC_ALL"] = ""
set_locale!(LocaleId(""), LC.ALL)
@testset "clocale identifiers from envionment for $sym" for sym in ALLCAT
@test clocale_id(sym) == clocid
end
@testset "clocale codesets from environment for $sym" for sym in ALLCAT
try
nli = eval(CLocales, Meta.parse(string(sym, "_CODESET")))
@test nl_langinfo(nli) == "UTF-8"
end
end
@testset "setting and querying clocalesi prog" begin
@test clocale_id(LC.NUMERIC) == "fr_FR.utf8"
set_locale!(LocaleId("C"))
set_locale!(LocaleId("tr_TR"), LC.MESSAGES)
set_locale!(LocaleId("en-us"), LC.MONETARY)
@test clocale_id(LC.CTYPE) == "C"
@test clocale_id(LC.NUMERIC) == "C"
@test clocale_id(LC.MESSAGES) == "tr_TR.utf8"
@test clocale_id(LC.MONETARY) == "en_US.utf8"
end
ENV["LC_ALL"] = "de_DE.utf8"
set_locale!(LocaleId(""), LC.MESSAGES | LC.NAME)
@testset "setting and querying clocales ENV" begin
@test clocale_id(LC.NUMERIC) == "C"
@test clocale_id(LC.MESSAGES) == "de_DE.utf8"
@test clocale_id(LC.NAME) == "de_DE.utf8"
@test clocale_id(LC.MONETARY) == "en_US.utf8"
end
import .CLocales:
CTYPE_CODESET,
RADIXCHAR, THOUSEP, THOUSANDS_SEP, GROUPING, NUMERIC_CODESET,
ABDAY, DAY, ABMON, MON, AM_STR, PM_STR, D_T_FMT, D_FMT, T_FMT, T_FMT_AMPM, ERA,
ERA_YEAR, ERA_D_FMT, ALT_DIGITS, ERA_D_T_FMT, ERA_T_FMT, TIME_CODESET,
COLLATE_CODESET,
YESEXPR, NOEXPR, YESSTR, NOSTR, MESSAGES_CODESET,
INT_CURR_SYMBOL, CURRENCY_SYMBOL, MON_DECIMAL_POINT, MON_THOUSANDS_SEP, MON_GROUPING,
POSITIVE_SIGN, NEGATIVE_SIGN, INT_FRAC_DIGITS, FRAC_DIGITS, P_CS_PRECEDES, P_SEP_BY_SPACE,
N_CS_PRECEDES, N_SEP_BY_SPACE, P_SIGN_POSN, N_SIGN_POSN, CRNCYSTR, INT_P_CS_PRECEDES,
INT_P_SEP_BY_SPACE, INT_N_CS_PRECEDES, INT_N_SEP_BY_SPACE, INT_P_SIGN_POSN, INT_N_SIGN_POSN,
MONETARY_CODESET,
PAPER_HEIGHT, PAPER_WIDTH, PAPER_CODESET,
NAME_FMT, NAME_GEN, NAME_MR, NAME_MRS, NAME_MISS, NAME_MS, NAME_CODESET,
ADDRESS_POSTAL_FMT, ADDRESS_COUNTRY_NAME, ADDRESS_COUNTRY_POST, ADDRESS_COUNTRY_AB2,
ADDRESS_COUNTRY_AB3, ADDRESS_COUNTRY_CAR, ADDRESS_COUNTRY_NUM, ADDRESS_COUNTRY_ISBN,
ADDRESS_LANG_NAME, ADDRESS_LANG_AB, ADDRESS_LANG_LIB, ADDRESS_LANG_TERM, ADDRESS_CODESET,
TELEPHONE_TEL_INT_FMT, TELEPHONE_TEL_DOM_FMT, TELEPHONE_INT_SELECT, TELEPHONE_INT_PREFIX,
TELEPHONE_CODESET,
MEASUREMENT, MEASUREMENT_CODESET,
IDENTIFICATION_TITLE, IDENTIFICATION_SOURCE, IDENTIFICATION_ADDRESS, IDENTIFICATION_CONTACT,
IDENTIFICATION_EMAIL, IDENTIFICATION_TEL, IDENTIFICATION_FAX, IDENTIFICATION_LANGUAGE,
IDENTIFICATION_TERRITORY, IDENTIFICATION_AUDIENCE, IDENTIFICATION_APPLICATION, IDENTIFICATION_ABBREVIATION,
IDENTIFICATION_REVISION, IDENTIFICATION_DATE, IDENTIFICATION_CATEGORY, IDENTIFICATION_CODESET
const DE_ITEMS = [
RADIXCHAR => ",",
THOUSEP => ".",
THOUSANDS_SEP => ".",
GROUPING => 3,
ABDAY(2) => "Mo",
DAY(1) => "Sonntag",
DAY(7) => "Samstag",
ABMON(6) => "Jun",
MON(6) => "Juni",
AM_STR => "",
PM_STR => "",
D_T_FMT => "%a %d %b %Y %T %Z",
D_FMT => "%d.%m.%Y",
T_FMT => "%T",
T_FMT_AMPM => "",
ERA => "",
ERA_YEAR => "",
ERA_D_FMT => "",
ALT_DIGITS => "",
ERA_D_T_FMT => "",
ERA_T_FMT => "",
YESEXPR => "^[jJyY].*",
NOEXPR => "^[nN].*",
INT_CURR_SYMBOL => "EUR ",
CURRENCY_SYMBOL => "€" ,
MON_DECIMAL_POINT => ",",
MON_THOUSANDS_SEP => ".",
MON_GROUPING => 3,
POSITIVE_SIGN => "",
NEGATIVE_SIGN => "-",
INT_FRAC_DIGITS => 2,
FRAC_DIGITS => 2,
P_CS_PRECEDES => 0,
P_SEP_BY_SPACE => 1,
N_CS_PRECEDES => 0,
N_SEP_BY_SPACE => 1,
P_SIGN_POSN => 1 ,
N_SIGN_POSN => 1,
CRNCYSTR => "+€",
INT_P_CS_PRECEDES => 0,
INT_P_SEP_BY_SPACE => 1,
INT_N_CS_PRECEDES => 0,
INT_N_SEP_BY_SPACE => 1,
INT_P_SIGN_POSN => 1,
INT_N_SIGN_POSN => 1,
PAPER_HEIGHT => 297,
PAPER_WIDTH => 210,
NAME_FMT => "%d%t%g%t%m%t%f",
NAME_GEN => "",
NAME_MR => "Herr",
NAME_MRS => "Frau",
NAME_MISS => "Fräulein",
NAME_MS => "Frau",
ADDRESS_POSTAL_FMT => "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
ADDRESS_COUNTRY_NAME => "Deutschland",
ADDRESS_COUNTRY_POST => "D",
ADDRESS_COUNTRY_AB2 => "DE",
ADDRESS_COUNTRY_AB3 => "DEU",
ADDRESS_COUNTRY_CAR => "D",
ADDRESS_COUNTRY_NUM => 276,
ADDRESS_COUNTRY_ISBN => "3",
ADDRESS_LANG_NAME => "Deutsch",
ADDRESS_LANG_AB => "de",
ADDRESS_LANG_LIB => "deu",
ADDRESS_LANG_TERM => "ger",
TELEPHONE_TEL_INT_FMT => "+%c %a %l",
TELEPHONE_TEL_DOM_FMT => "%A %l",
TELEPHONE_INT_SELECT => "00",
TELEPHONE_INT_PREFIX => "49",
MEASUREMENT => 1,
IDENTIFICATION_TITLE => "German locale for Germany",
IDENTIFICATION_SOURCE => "Free Software Foundation, Inc.",
IDENTIFICATION_ADDRESS => "http://www.gnu.org/software/libc/",
IDENTIFICATION_CONTACT => "",
IDENTIFICATION_EMAIL => "[email protected]",
IDENTIFICATION_TEL => "",
IDENTIFICATION_FAX => "",
IDENTIFICATION_LANGUAGE => "German",
IDENTIFICATION_TERRITORY => "Germany",
IDENTIFICATION_AUDIENCE => "",
IDENTIFICATION_APPLICATION => "",
IDENTIFICATION_ABBREVIATION => "",
IDENTIFICATION_REVISION => "1.0",
IDENTIFICATION_DATE => "2000-06-24",
IDENTIFICATION_CATEGORY => "de_DE:2000",
]
set_locale!(LocaleId("de-de")) # set all categories
@testset "nl_langinfo queries $(category(p.first))-$(offset(p.first)) => '$(p.second)'" for p in DE_ITEMS
item, res = p
@test nl_langinfo(item) == res
end
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 208 |
using Test
using ResourceBundles
using ResourceBundles.CLocales
function localized_isless(loc::LocaleId)
function lt(a::AbstractString, b::AbstractString)
strcollate(a, b, loc) < 0
end
end
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 1008 |
### accessing libc functions (XOPEN_SOURCE >= 700, POSIX_C_SOURCE >= 200809L glibc>=2.24)
using ResourceBundles.CLocales
using .LC
import .CLocales: newlocale_c, strcoll_c, nl_langinfo_c
const P0 = Ptr{Nothing}(0)
@test newlocale_c(LC._MASK_ALL, "invalidxxx", P0) == P0
COLL_C = [
("a", "b", -1),
("A", "b", -1),
("a", "B", +1),
]
COLL_en = [
("a", "b", -1),
("A", "b", -1),
("a", "B", -1),
]
@testset "C-locale for $loc" for (loc, COLL) in (("C", COLL_C), ("en_US.utf8", COLL_en))
test_locale = newlocale_c(LC._MASK_ALL, loc, P0)
if test_locale != P0
@test duplocale(test_locale) != P0
@test unsafe_string(nl_langinfo_c(Cint(0xffff), test_locale)) == loc
@testset "string comparisons '$a' ~ '$b'" for (a, b, r) in COLL
@test sign(strcoll_c(a, b, test_locale)) == r
end
@test freelocale(test_locale) === nothing
else
@info "no C-locale defined for '$loc'"
end
end
#################################
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 6026 | using .Locales
using .LC
# Construct LocaleId from language tags
@test LocaleId("") === DEFAULT
@test LocaleId("C") === ROOT
@test LocaleId("en") === ENGLISH
@test LocaleId("en-US") === US
@test_throws ArgumentError("missing language prefix") LocaleId("c")
@test string(LocaleId("de")) == "de"
@test string(LocaleId("de_latn")) == "de_Latn"
@test string(LocaleId("de-de")) == "de_DE"
@test string(LocaleId("de-111")) == "de_111"
@test string(LocaleId("de-variAnt1")) == "de_variant1"
@test string(LocaleId("de-variAnt1_varia2")) == "de_variant1_varia2"
@test string(LocaleId("de-1erw-varia2")) == "de_1erw_varia2"
@test string(LocaleId("de-a_aB")) == "de_a_ab"
@test string(LocaleId("DE_X_1_UZ_A_B")) == "de_x_1_uz_a_b"
@test string(LocaleId("DE_latn_de")) == "de_Latn_DE"
@test string(LocaleId("DE_latn_de-variant1")) == "de_Latn_DE_variant1"
@test string(LocaleId("DE_latn_de_a-uu-11")) == "de_Latn_DE_a_uu_11"
@test string(LocaleId("DE_latn_de-varia-a-uu-11")) == "de_Latn_DE_varia_a_uu_11"
@test string(LocaleId("DE_latn_de-varia-a-uu-11")) == "de_Latn_DE_varia_a_uu_11"
@test string(LocaleId("DE_latn_de-1var-a-uu-11")) == "de_Latn_DE_1var_a_uu_11"
@test string(LocaleId("DE_latn_de-1va2-a-uu-11")) == "de_Latn_DE_1va2_a_uu_11"
@test string(LocaleId("DE_latn_de-x-11-a-uu-11")) == "de_Latn_DE_x_11_a_uu_11"
@test string(LocaleId("DE_latn_de-b-22-a-uu-11")) == "de_Latn_DE_a_uu_11_b_22"
@test string(LocaleId("DE_latn_de-z-22-a-uu-11")) == "de_Latn_DE_a_uu_11_z_22"
@test string(LocaleId("zh-han")) == "han"
@test string(LocaleId("deu")) == "de"
@test LocaleId("en") ⊆ LocaleId("C")
@test BOTTOM ⊆ LocaleId("en-Latn-ab-valencia-a-bc-x-1-2")
@test LocaleId("en-a-aa-b-bb") ⊆ LocaleId("en-b-bb")
@test hash(LocaleId("is-a-aa-b-bb")) == hash(LocaleId("is-b-bb-a-aa"))
@test LocaleId("is-a-aa-b-bb") === LocaleId("is-b-bb-a-aa")
@test LocaleId("C") != LocaleId("")
# exceptions
create2(l="", lex=String[], s="", r="", v=String[], d=Dict{Char,Vector{Symbol}}()) =
create_locid(l, lex, s, r, v, d)
@test_throws ArgumentError("missing language prefix") LocaleId("a-ab")
@test_throws ArgumentError("no language prefix 'a'") LocaleId("a", "")
@test_throws ArgumentError("only one language extension allowed 'de_abc_def'") LocaleId("de-abc-def")
@test_throws ArgumentError("no language exensions allowed 'abcd_def'") create2("abcd", ["def"])
@test_throws ArgumentError("no script 'Abc'") LocaleId("ab", "abc", "de")
@test_throws ArgumentError("no region 'DEF'") LocaleId("ab", "abcd", "def")
@test_throws ArgumentError("no variants 'vari'") create2("ab", String[], "", "", ["vari"])
@test_throws ArgumentError("no variants '1va'") create2("ab", String[], "", "", ["1va"])
@test_throws ArgumentError("no variants 'asdfghjkl'") create2("ab", String[], "", "", ["asdfghjkl"])
@test_throws ArgumentError("no variants '1990_asdfghjkl'") create2("ab", String[], "", "", ["1990", "asdfghjkl"])
@test_throws ArgumentError("language tag contains invalid characters: 'Ä'") LocaleId("Ä")
@test_throws ArgumentError("multiple occurrence of singleton 'u'") LocaleId("en-u-u1-u-u2")
@test_throws ArgumentError("no language tag: 'en_asdfghjkl' after 1") LocaleId("en_asdfghjkl")
@test_throws ArgumentError("no language tag: 'asdfghjkl' after 0") LocaleId("asdfghjkl")
@test_throws ArgumentError("no language tag: 'x_asdfghjkl' after 1") LocaleId("x-asdfghjkl")
@test_throws ArgumentError("too many language extensions 'en_abc_def_ghi_jkl'") LocaleId("en-abc-def-ghi-jkl")
#various constructors
@test LocaleId("") === DEFAULT
@test LocaleId("C") === ROOT
@test LocaleId() === BOTTOM
@test LocaleId("de", "de") == LocaleId("de-de")
@test LocaleId("de", "latn", "de") == LocaleId("de-Latn-de")
@test LocaleId("de", "latn", "de", "bavarian") == LocaleId("de-Latn-de-bavarian")
@test LocaleId("de", "de") == LocaleId("de-de")
@test LocaleId("de", "de") == LocaleId("de-de")
@test LocaleId("de", "de") == LocaleId("de-de")
@test LocaleId("de", "de") == LocaleId("de-de")
# predefined locales
@test ENGLISH === LocaleId("en")
@test FRENCH === LocaleId("fr")
@test GERMAN === LocaleId("de")
@test ITALIAN === LocaleId("it")
@test JAPANESE === LocaleId("ja")
@test KOREAN === LocaleId("ko")
@test CHINESE === LocaleId("zh")
@test SIMPLIFIED_CHINESE === LocaleId("zh_CN")
@test TRADITIONAL_CHINESE === LocaleId("zh_TW")
@test FRANCE === LocaleId("fr_FR")
@test GERMANY === LocaleId("de_DE")
@test ITALY === LocaleId("it_IT")
@test JAPAN === LocaleId("ja_JP")
@test KOREA === LocaleId("ko_KR")
@test CHINA === LocaleId("zh_CN")
@test PRC === LocaleId("zh_CN")
@test TAIWAN === LocaleId("zh_TW")
@test UK === LocaleId("en_GB")
@test US === LocaleId("en_US")
@test CANADA === LocaleId("en_CA")
# inclusion and ordering
@test LocaleId() ⊆ LocaleId("en-Latf-gb-variant-variant2-a-123-26-x-1-2-23a-bv")
@test LocaleId("en-Latf-gb-variant-variant2-a-123-26-x-1-2-23a-bv") ⊆ LocaleId("")
@test !(LocaleId("fr-Latn") ⊆ LocaleId("fr-CA"))
@test !(LocaleId("fr-CA") ⊆ LocaleId("fr-Latn"))
@test !(LocaleId("fr-Latn") < LocaleId("fr-CA"))
@test LocaleId("fr-Latn") ≥ LocaleId("fr-CA")
# loading initial values from environment variables
delete!(ENV, "LANG")
delete!(ENV, "LC_MESSAGES")
delete!(ENV, "LC_COLLATE")
delete!(ENV, "LC_TIME")
delete!(ENV, "LC_NUMERIC")
delete!(ENV, "LC_MONETARY")
ENV["LC_ALL"] = "en_GB"
@test default_locale(LC.MESSAGES) === LocaleId("en-GB")
ENV["LC_ALL"] = "en_GB.utf8"
@test default_locale(LC.COLLATE) === LocaleId("en-GB")
ENV["LC_ALL"] = "en_GB.utf8@oed"
@test default_locale(LC.TIME) === LocaleId("en-GB-x-posix-oed")
ENV["LC_ALL"] = "en_GB@oed"
@test default_locale(LC.NUMERIC) === LocaleId("en-GB-x-posix-oed")
delete!(ENV, "LC_ALL")
ENV["LC_MONETARY"] = "en_US.UTF-8"
@test default_locale(LC.MONETARY) === LocaleId("en-US")
ENV["LC_TIME"] = "en_CA"
@test default_locale(LC.TIME) === LocaleId("en-ca")
ENV["LC_TIME"] = ""
delete!(ENV, "LC_MONETARY")
ENV["LANG"] = "fr_FR@guadelo"
@test default_locale(LC.TIME) === LocaleId("fr-FR-x-posix-guadelo")
ENV["LANG"] = "C"
@test default_locale(LC.TIME) === LocaleId("C")
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 5891 | using Logging
bundle = ResourceBundle(@__MODULE__, "messages2")
@test bundle.path == abspath("resources")
bundle2 = ResourceBundle(ResourceBundles, "bundle")
@test realpath(bundle2.path) == realpath(normpath(pwd(), "resources"))
bundle3 = ResourceBundle(ResourceBundles, "does1not2exist")
@test bundle3.path == "."
bundle4 = ResourceBundle(Test, "XXX")
@test bundle4.path == "."
@test_throws ArgumentError ResourceBundle(Main, "")
@test_throws ArgumentError ResourceBundle(Main, "d_n_e")
const results = Dict(
(LocaleId("C"), "T0") => "T0",
(LocaleId("C"), "T1") => "T1 - empty",
(LocaleId("C"), "T2") => "T2 - empty",
(LocaleId("C"), "T3") => "T3 - empty",
(LocaleId("C"), "T4") => "T4 - empty",
(LocaleId("C"), "T5") => "T5 - empty",
(LocaleId("C"), "T6") => "T6",
(LocaleId("C"), "T7") => "T7",
(LocaleId("en"), "T0") => "T0",
(LocaleId("en"), "T1") => "T1 - empty",
(LocaleId("en"), "T2") => "T2 - en",
(LocaleId("en"), "T3") => "T3 - en",
(LocaleId("en"), "T4") => "T4 - en",
(LocaleId("en"), "T5") => "T5 - en",
(LocaleId("en"), "T6") => "T6",
(LocaleId("en"), "T7") => "T7",
(LocaleId("en-US"), "T0") => "T0",
(LocaleId("en-US"), "T1") => "T1 - empty",
(LocaleId("en-US"), "T2") => "T2 - en",
(LocaleId("en-US"), "T3") => "T3 - en_US",
(LocaleId("en-US"), "T4") => "T4 - en",
(LocaleId("en-US"), "T5") => "T5 - en_US",
(LocaleId("en-US"), "T6") => "T6 - en_US",
(LocaleId("en-US"), "T7") => "T7 - en_US",
(LocaleId("en-Latn"), "T0") => "T0",
(LocaleId("en-Latn"), "T1") => "T1 - empty",
(LocaleId("en-Latn"), "T2") => "T2 - en",
(LocaleId("en-Latn"), "T3") => "T3 - en",
(LocaleId("en-Latn"), "T4") => "T4 - en_Latn",
(LocaleId("en-Latn"), "T5") => "T5 - en_Latn",
(LocaleId("en-Latn"), "T6") => "T6 - en_Latn",
(LocaleId("en-Latn"), "T7") => "T7",
(LocaleId("en-Latn-US"), "T0") => "T0",
(LocaleId("en-Latn-US"), "T1") => "T1 - empty",
(LocaleId("en-Latn-US"), "T2") => "T2 - en",
(LocaleId("en-Latn-US"), "T3") => "T3 - en_US",
(LocaleId("en-Latn-US"), "T4") => "T4 - en_Latn",
(LocaleId("en-Latn-US"), "T5") => "T5 - en_Latn_US",
(LocaleId("en-Latn-US"), "T6") => ("T6 - en_Latn", "Ambiguous"),
(LocaleId("en-Latn-US"), "T7") => "T7 - en_US",
(LocaleId("en-x-1"), "T0") => "T0",
(LocaleId("en-x-1"), "T1") => "T1 - empty",
(LocaleId("en-x-1"), "T2") => "T2 - en",
(LocaleId("en-x-1"), "T3") => "T3 - en",
(LocaleId("en-x-1"), "T4") => "T4 - en",
(LocaleId("en-x-1"), "T5") => "T5 - en",
(LocaleId("en-x-1"), "T6") => "T6",
(LocaleId("en-x-1"), "T7") => "T7",
)
locs = LocaleId.(("C", "en", "en-US", "en-Latn", "en-Latn-US", "en-x-1"))
keya = ((x->"T" * string(x)).(0:7))
log = Test.TestLogger(min_level=Logging.Warn)
locm = locale_id(LC.MESSAGES)
@testset "message lookup for locale $loc and key $key" for loc in locs, key in keya
res = results[loc, key]
if isa(res, Tuple)
r, w = res
else
r, w = res, ""
end
with_logger(log) do
@test get(bundle, loc, key, key) == r
@test test_log(log, w)
set_locale!(loc, LC.MESSAGES)
@test get(bundle, key, key) == r
test_log(log, w)
end
end
set_locale!(locm, LC.MESSAGES)
with_logger(log) do
@test keys(bundle, LocaleId("")) == ["T1", "T2", "T3", "T4", "T5"]
@test keys(bundle, LocaleId("de")) == ["T1", "T2", "T3", "T4", "T5"]
@test keys(bundle2) == []
@test test_log(log)
@test keys(bundle, LocaleId("de-us")) == ["T1", "T2", "T3", "T4", "T5"]
@test test_log(log, "Wrong type 'Dict{Int64,Int64}'")
@test keys(bundle, LocaleId("de-us-america")) == ["T1", "T2", "T3", "T4", "T5"]
@test test_log(log, "Wrong type 'String'")
@test keys(bundle, LocaleId("de-us-america-x-1")) == ["T1", "T2", "T3", "T4", "T5"]
@test test_log(log, "Wrong type 'Nothing'")
@test keys(bundle3, LocaleId("")) == String[]
@test keys(bundle) == ["T1", "T2", "T3", "T4", "T5", "T6", "T7", "hello"]
end
@test resource_bundle(@__MODULE__, "messages2") === RB_messages2
@test resource_bundle(@__MODULE__, "bundle") === RB_bundle
@test @resource_bundle("d1n2e").path == ""
bundlea = @resource_bundle("bundle")
@test bundlea === RB_bundle
# Test in submodule Main.XXX
module XXX
using ResourceBundles, Test
@test @resource_bundle("messages2") === RB_messages2
@test Main.XXX.RB_messages2 === Main.RB_messages2
@test @resource_bundle("bundle") === RB_bundle
@test Main.XXX.RB_bundle !== Main.RB_bundle
# Test in submodule Main.XXX.YYY
module YYY
using ResourceBundles, Test
@test @resource_bundle("bundle") === RB_bundle
@test Main.XXX.YYY.RB_bundle === Main.XXX.RB_bundle
end
end
@test resource_bundle(ResourceBundles, "messages2") === ResourceBundles.RB_messages2
@test resource_bundle(ResourceBundles, "bundle") === ResourceBundles.RB_bundle
bundlea = ResourceBundles.eval(:(@resource_bundle("bundle")))
@test bundlea === ResourceBundles.RB_bundle
# test in submodule ResourceBundles.XXX
ResourceBundles.eval(:(module XXX
using ResourceBundles, Test
@test string(@__MODULE__) == "ResourceBundles.XXX"
@test @resource_bundle("messages2") === RB_messages2
@test ResourceBundles.XXX.RB_messages2 === ResourceBundles.RB_messages2
@test @resource_bundle("bundle") === RB_bundle
@test ResourceBundles.XXX.RB_bundle !== ResourceBundles.RB_bundle
end )
)
lpa = ResourceBundles.locale_pattern
sep = Base.Filesystem.path_separator
@test lpa(".jl") == LocaleId("C")
@test lpa("-en.jl") == LocaleId("en")
@test lpa("_en.jl") == LocaleId("en")
@test lpa(sep*"en.jl") == LocaleId("en")
@test lpa("-en"*sep*".jl") == LocaleId("en")
@test lpa(sep*"en"*sep*".jl") == LocaleId("en")
@test lpa(sep*"en."*sep*"jl") == nothing
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 1162 | test = VERSION >= v"0.7-DEV" ? :(using Test) : :(using Base.Test)
eval(test)
using Logging
using ResourceBundles
import ResourceBundles: ROOT, BOTTOM, create_locid
import ResourceBundles: set_locale!, load_file
cd(abspath(pathof(ResourceBundles), "..", ".."))
# test if logger contains text in a message; finally with:clear logger.
function test_log(log::Test.TestLogger, text::AbstractString)
try
isempty(text) && return test_log(log)
conmess(x::Test.LogRecord) = occursin(text, x.message)
any(conmess.(test_log_filter(log)))
finally
empty!(log.logs)
end
end
test_log(log::Test.TestLogger) = isempty(test_log_filter(log))
# ignore messages from Core module
test_log_filter(log::Test.TestLogger) = filter(lr->lr._module != Core, log.logs)
@testset "types" begin include("types.jl") end
@testset "locale" begin include("locale.jl") end
@testset "resource_bundle" begin include("resource_bundle.jl") end
@testset "string" begin include("string.jl") end
@testset "libc" begin include("libc.jl") end
# @testset "clocale" begin include("clocale.jl") end
# @testset "localetrans" begin include("localetrans.jl") end
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 3756 | using Logging
using .LC
const a1 = "arg1"
const a2 = "arg2"
const a3 = 4711
const h0 = 0
const h1 = 1
const hmany = 13
city = "Frankfurt"
temp = 29.0
ndhi = 15
set_locale!(LocaleId("en-us"), LC.MESSAGES)
@test tr"T3" == "T3 - en_US"
@test tr"original $a1($a2) : $(a3*2)" == "US version $(a3*2) / $a2 $a1"
# test with invalid plural forms
@test_throws ArgumentError tr"error1"
@test tr"error2 $h1" == "error2a"
# attention: en-US defines a non-standard plurals rule
@test tr"missing argument value $(99)" == "missing argument value 99"
@test tr"These are $h1 houses" == "This is a house"
@test tr"These are $hmany houses" == "These are at least $(hmany) houses"
@test tr"These are $(0) houses" == "This is not a house"
@test tr"These are $(hmany-hmany) houses" == "This is not a house"
set_locale!(LocaleId("fr"), LC.MESSAGES)
@test tr"original $a1($a2) : $(a3*2)" == "original $a1($a2) : $(a3*2)"
@test tr"These are $(1) houses" == "C'est 1 maison"
@test tr"These are $(hmany*3+3) houses" == "Ce sont beaucoup(42) de maisons"
@test tr"These are $(10) houses" == "Ce sont beaucoup(10) de maisons"
@test tr"These are $h0 houses" == "C'est 0 maison"
# data for this locale are stored in po-file
set_locale!(LocaleId("de-AT"), LC.MESSAGES)
@test tr"These are $(1) houses" == "Das ist ein Haus"
@test tr"These are $(hmany*3+3) houses" == "Das sind 42 Häuser"
@test tr"These are $(10) houses" == "Das sind 10 Häuser"
@test tr"These are $h0 houses" == "Das sind 0 Häuser"
@test tr"In $(city) the temperature was above $(temp) °C" == "Die Temperatur von $(temp) °C wurde in $(city) überschritten"
@test tr"In $(city) the temperature was above $(temp) °C at $(!ndhi) days" == "In $(city) war die Temperatur an $(ndhi) Tagen über $(temp) °C"
@test tr"In $(city) the temperature was above $(temp) °C at $(!h1) days" == "In $(city) war die Temperatur an einem \"Tag\" über $(temp) °C"
# Permutations
@test tr"123 $(1) $(2) $(3)" == "123 1 2 3"
@test tr"132 $(1) $(2) $(3)" == "132 1 3 2"
@test tr"213 $(1) $(2) $(3)" == "213 2 1 3"
@test tr"213 $(1) $(2) $(3)" == "213 2 1 3"
@test tr"312 $(1) $(2) $(3)" == "312 3 1 2"
@test tr"321 $(1) $(2) $(3)" == "321 3 2 1"
# Primary Forms
@test tr"123 $(1) $(!2) $(3)" == "123 1 2 3"
@test tr"132 $(1) $(!2) $(3)" == "132 1 3 2" #
@test tr"213 $(1) $(!2) $(3)" == "213 2 1 3"
@test tr"213 $(1) $(!2) $(3)" == "213 2 1 3"
@test tr"312 $(1) $(!2) $(3)" == "312 3 1 2" #
@test tr"321 $(1) $(!2) $(3)" == "321 3 2 1" #
@test tr"123 $(1) $(2) $(!3)" == "123 1 2 3" #
@test tr"132 $(1) $(2) $(!3)" == "132 1 3 2" #
@test tr"213 $(1) $(2) $(!3)" == "213 2 1 3" #
@test tr"213 $(1) $(2) $(!3)" == "213 2 1 3" #
@test tr"312 $(1) $(2) $(!3)" == "312 3 1 2" #
@test tr"321 $(1) $(2) $(!3)" == "321 3 2 1" #
# Context
@test tr"§testctx§original" == "O r i g i n a l"
# evoke warnings when reading files
log = Test.TestLogger(min_level=Logging.Info)
with_logger(log) do
load_file(joinpath("resources", "messages.pox"))
end
mess = isempty(log.logs) ? "" : log.logs[1].message
@test occursin("invalid extension of file name", mess)
empty!(log.logs)
with_logger(log) do
load_file(joinpath("resources", "messages_tv.po"))
end
mess = isempty(log.logs) ? "" : log.logs[1].message
@test occursin("unexpected msgid", mess)
@test string_to_key("simple") == "simple"
@test string_to_key(raw"with $v1 and $(expr+2)") == raw"with $(1) and $(2)"
@test string_to_key(raw"with $v1 and $(!(expr+2))") == raw"with $(2) and $(1)"
# data for this locale are stored in little-endian mo-file
set_locale!(LocaleId("de-LU"), LC.MESSAGES)
@test tr"§testctx§original" == "O r i g i n a l"
# data for this locale are stored in big-endian mo-file
set_locale!(LocaleId("de-CH"), LC.MESSAGES)
@test tr"§testctx§original" == "O r i g i n a l"
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | code | 463 |
using ResourceBundles.LC
lca = LC.ALL
lct = LC.TIME
lci = LC.IDENTIFICATION
lcc = LC.CTYPE
@test lca ⊆ lca
@test lct ⊆ lca
@test !(lca ⊆ lct)
@test lct ⊆ lct
@test lci ⊆ lct | lci
@test lca | lct === lca
@test lci | lci === lci
@test lci | lct === lct | lci
@test lci | lct ⊆ lct | lci
@test lci | lct ⊆ lca
@test lcc | lci | lct | lci === lci | lct | lcc
@test collect(lci) == [lci]
@test collect(lci | lct) == [lct, lci]
@test length(collect(lca )) == 12
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"MIT"
] | 0.2.0 | 9d3e825b839eaab818af0df94f7fc9b3ead3fc90 | docs | 12300 | # ResourceBundles
[](https://travis-ci.org/KlausC/ResourceBundles.jl)
[](http://codecov.io/github/KlausC/ResourceBundles.jl?branch=master)
## ResourceBundles is a package to support Internationalization (I18n).
Main features:
### Locale
* create Locale from string formed according to standards Unicode Locale Identifier (BCP47 (tags for Identifying languages), RFC5646, RFC4647)
* set/get default locale for different purposes
* startup-locale derived form environment settings (LANG, LC_MESSAGES, ..., LC_ALL)
* Locale patterns imply a canonical partial ordering by set inclusion
### ResourceBundle
* Database of objects (e.g. text strings), identified by locale and individual text key
* select most specific available object according to canonical ordering of locales
* detect ambiguities for individual keys
* storage in package module directory
* database uses files witten in Julia source code
* database files containing translated texts using gettext-PO format is supported
#### Message text localization (LC_MESSAGES)
* a string macro providing translation of standard language according to default locale
* support string interpolation and control ordering of interpolated substrings
* includes mechanism for multiple plural forms for translations
* fall back to text provided as key within the source text
* Define global default Resource bundle for each module
* Support features of Posix `gettext`
#### NumberFormat and DateTimeFormat (LC_NUMERIC, LC_TIME) (TODO)
* If an object is formatted in the interpolation context of a translated string, instead of the usual `show` method, a locale sensitive replacement is called.
* those methods default to the standard methods, if not explicitly defined.
* For real numbers and date or time objects, methods can be provided as locale dependent resources.
#### String comparison (LC_COLLATE) (TODO)
* Strings containing natural language texts are sorted locale-sensitive according to
"Unicode Collation Algorithm". Implementation makes use of `ICU` if possible. In order to treat a string as natural text, it is wrapped by a `NlsString` object.
#### Character Classes (LC_CTYPE) (TODO)
* Character classification (`isdigit`, `isspace` ...) and character or string transformations
(`uppercase`, `titlecase`, ...) are performed locale-sensitive for wrapped types.
### Installation
```
# assuming a unix shell
cd ~/.julia/dev
git clone http://github.com/KlausC/ResourceBundles.jl ResourceBundles
]add ResourceBundles
```
### Usage
```
using ResourceBundles
# The following code is to make the test resources of ResourceBundles itself available
# to the Main module. Typically the resources are accessible within their module.
rdir = abspath(pathof(ResourceBundles), "..", "..", "resources")
;ln -s $rdir .
# show current locale (inherited from env LC_ALL, LC_MESSAGES, LANG)
locale()
# change locale for messages programmatically:
set_locale!(LocaleId("de"), LC.MESSAGES)
# use string translation feature
println(tr"original text")
for n = (2,3)
println(tr"$n dogs have $(4n) legs")
end
for lines in [1,2,3]
println(tr"$lines lines of code")
end
# access the posix locale definitions
ResourceBundles.CLocales.nl_langinfo(ResourceBundles.CLocales.CURRENCY_SYMBOL)
```
sample configuration files in directory `pathof(MyModule)/../../resources`
```
cat messages_de.po
#
# Comments
#
# Empty msgid containing options - only Plural-Forms is used
msgid ""
msgstr "other options\n"
"Plural-Forms: nplurals = 3; plural = n == 1 ? 0 : n == 2 ? 1 : 3\n"
"other options: \n"
#: main.jl:6 (used as a comment)
msgid "original text"
msgstr "Originaltext"
#: main.jl:7
msgid "$(1) dogs have $(2) legs"
msgstr "$(2) Beine gehören zu $(1) Hunden"
#: main.jl:9
msgid "$(1) lines of code"
msgstr[0] "eine Zeile"
msgstr[1] "Zeilenpaar"
msgstr[2] "$(1) Zeilen"
```
or alternatively, with same effect
```
cat messages_de.jl
( "" => "Plural-Forms: nplurals = 3; plural = n == 1 ? 0 : n == 2 ? 1 : 3"
"original text" => "Originaltext",
raw"$(1) dogs have $(2) legs" => raw"$(2) Beine gehören zu $(1) Hunden",
raw"$(1) lines of code" => ["eine Zeile", """Zeilenpaar""", raw"$(1) Zeilen"],)
```
expected output:
```
Originaltext
12 Beine gehören zu 3 Hunden
0 Zeilen
1 Zeile
ein Zeilenpaar
3 Zeilen
```
## User Guide
#### Locale Identifiers and Locales
Locale Identifiers are converted from Strings, which are formatted according to Unicode Locale Identifier.
Examples: "en", "en_Latn", "en_US", "en_Latn_GB_london", "en_US_x_private".
Additionally the syntax for Posix environment variables `LANG` and `LC_...` are
supported.
Examples: "C", "en_US", "en_us.utf8", "en_US@posext".
All those formats are converted to a canonical form and stored in objects of type `LocaleID`: `LocaleID("en_US")`.
The `_` may be replaced by `-` in input.
`LocaleId` implements the `equals` and the `issubset` (`⊆`) relations.
Here `LocaleId("en_US") ⊆ LocaleId("en") ⊆ LocaleId("C") == LocaleId("")`.
The `Locale` is a set of locale-properties for several categories. The categories are taken
from the GNU implementation. Each locale-property is identified by a `LocaleId`.
Each category corresponds to one of the `LC_` environment variables and there is a related
constant in module 'LC'. Here is the complete list:
category | remark
-------------------------------
CTYPE | character classifications (letter, digit, ...)
NUMERIC | number formating (decimal separator, ...)
TIME | time and date formats
COLLATE | text comparison
MONETARY | currency symbol
MESSAGES | translation of message texts
ALL | not a category - used to override all other settings
PAPER | paper formats
NAME | person names
ADDRESS | address formating
TELEPHONE | formating of phone numbers
MEASUREMENT | measurement system (1 for metric, 2 for imperial)
IDENTIFICATION | name of the locale identifier
For all of those terms there is an environment variable `"LC_category"` and a Julia constant `LC.category`. The categories up to `ALL` are defined in POSIX(), which the others are GNU extensions.
The special variable `"LC_ALL"` overrides all other variables `"LC_category"` if set.
The additional environment variable `"LANG"` is used as a fallback, if neither `"LC_category"` nor `"LC_ALL"` is set.
Each task owns a task specific current locale. It is obtained by `locale()`.
For each category the valid locale identifier is accessed by `locale_id(LC.category)`.
For example the locale `locale_id(LC.MESSAGES)` is used as the default locale for message
text look-up in the current task.
The locale-ids of the current locale may be changed by `set_locale!(localeid, category)`.
For example `set_locale!(LocaleID("de_DE"), LC.MESSAGES)` modifies the current locale to
use German message translations.
All locale categories except for `LC.MESSAGES` are implemented by the GNU installation, which contains the shared library glibc, a set of predefined locale properties, and a tool `locales`, which delivers a list of all locale identifiers installed on the system.
In Julia, the values of all locale dependent variable of those categories may be obtained
like `ResourceBundles.CLocales.nl_langinfo.(ResourceBundles.CLocales.DAY.(1:7))`
or `ResourceBundles.CLocales.nl_langinfo(ResourceBundles.CLocales.IDENTIFICATION_TITLE)`.
These are only available on GNU based systems (including Linux and OSX).
#### Resource Bundles
A resource bundle is an association of string values with arbitrary objects, where the
actual mapping depends on a locale.
Conceptually it behaves like a `Dict{Tuple{String,Locale},Any}`.
Each resource bundle is bound to a package. The corresponding data are stored in the
subdirectory `resources` of the package directory.
`bundle = @resource_bundle("pictures")` creates a resource bundle, which is bound
to the current module. The resource is populated by the content found in the resource files, which are associated with the current module.
The resources are looked for the resources subdirectory of a package module or, if the
base module is `Main`, in the current working directory.
The object stored in reousource bundles are not restricted to strings, but may have any Julia type.
For example, it could make sense to store locale-dependent pictures (containing natural language texts) in resource bundles. Also locale dependent information or algorithms are possible.
The actual data of all resource bundles of a package stored in the package directory in an extra subdirectory named `resources` (`resource-dir>`. An individual resource bundle with name `<name>` consists of a collection of files with path names
`<resource-dir>/<name><intermediate>.[jl|po|mo]`.
Here `<intermediate>`may be empty or a canonicalized locale tag, whith separator characters replaced by `'_'` or `'/'`. That means, all files have the standard `Julia`extension (and they actually contain `Julia`code) or a `po`
extension indicating message resources in PO format. The files may be spread in a subdirectory hierarchy according to the structure of the languange tags.
Fallback strategy following structure of language tags.
#### String Translations
String translations make use of a current locale `(locale_id(LC.MESSAGES))` and a standard resource bundle `(@__MODULE__).RB_messages`, which is created on demand.
The macro `tr_str` allows the user to write texts in a standard locale and it is translated
at runtime to a corresponding text in the current locale.
It has the following features.
* translate plain text
* support string interpolation, allowing re-ordering of variables
* support multiple plural forms for exactly one interpolation variable
* support context specifiers
The interpolation expressions are embedded in the text of the string-macro `tr` in the usual
form, e.g. `tr" ... $var ... $(expr) ..."`.
If the programmer wants the text to be translated into one of several grammatical plural forms,
he has to formulate the text in the program in the plural form of the standard language and
embed at least one interpolation expression. One of those expressions has to be flagged by
the unary negation operator ( `tr" ... $(!expr) ... "`). The flagged expression must provide an
integer value. The negation operation is not executed, but indicates to the implementation,
which of several plural options has to be selected.
For this purpose the translation text database defines a "plural-formula", which maps the
integer expression `n` to a zero-based index. This index peeks the proper translation from a
vector of strings.
Some typical formulas in the PO-file format:
msgid ""
msgstr ""
"Plural-Forms: nplurals=1; plural=0;\n" # Chinese
"Plural-Forms: nplurals=1; plural=n > 1 ? 1 : 0;\n" # English (default)
"Plural-Forms: nplurals=1; plural=n == 1 ? 0 : 1;\n" # French
"Plural-Forms: nplurals=1; plural=n%10==1&&n%100!=11 ? 0 : n%10>=2&&n%10<=4&&(n%100<10||n%100>=20) ? 1 : 2;\n"
# Russian
For details see: [PO-Files](https://www.gnu.org/software/gettext/manual/gettext.html#PO-Files).
Message contexts are included in the tr string like `tr"§mood§blue"` or `tr"§color§blue"`. In the PO file it is defined for example like:
msgctx "mood"
msgid "blue"
msgstr "melancholisch"
msgctx "color"
msgid "blue"
msgstr "blau"
The `tr_str` macro includes the functionality of the gnu library calls `gettext`and `ngettext`.
The database supports the file formats and infrastructure defined by [gettext](https://www.gnu.org/software/gettext/manual). Also binary files with extension `.mo` are be processed, which can be compiled from `.po` files by the gettext-utility [`msgfmt`](https://www.gnu.org/software/gettext/manual/gettext.html#msgfmt-Invocation).
#### Limitations
The items labeled with `TODO` are not yet supported.
Windows is only supported for the LC_MESSAGES mechanisms, not the other locale categories.
| ResourceBundles | https://github.com/KlausC/ResourceBundles.jl.git |
|
[
"BSD-3-Clause",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | code | 837 | # This file is part of FlagSets.jl project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.
module FlagSets
#import Core.Intrinsics.bitcast
export FlagSet, flags, @flagset, @symbol_flagset
"""
FlagSet{FlagType,BaseType<:Integer} <: AbstractSet{FlagType}
Supertype of sets which are subsets of a finite universe of objects (flags),
where each set is encoded as an integer of type `BaseType`.
Flag sets are implemented similarly to `BitSet`s.
If `T <: FlagSet{B,F}`, then `typemax(T)` is a finite set of flags of type `F`.
If `set isa T`, then `set` is a subset of `typemax(T)`.
See [`@flagset`](@ref) and [`@flagset_type`](@ref) for more information.
"""
abstract type FlagSet{FlagType,BaseType<:Integer} <: AbstractSet{FlagType} end
include("interface.jl")
include("macros.jl")
end # module
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
|
[
"BSD-3-Clause",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | code | 5664 | # This file is part of FlagSets.jl project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.
function flagset_flags end
function flag_bit_map end
function flags end
function flagkeys end
"""
BitMask(bitmask::Integer)
Structure used internally by `FlagSets` for default constructor of subtypes of `FlagSet`.
"""
struct BitMask{T<:Integer}
bitmask::T
end
basetype(::Type{<:FlagSet{F,B}}) where {F,B<:Integer} = B
Base.isvalid(::Type{T}, x::Integer) where {T<:FlagSet} = (x & basetype(T)(typemax(T)) == x)
Base.isvalid(::Type{T}, x::BitMask) where {T<:FlagSet} = (x.bitmask & basetype(T)(typemax(T)) == x.bitmask)
Base.isvalid(::Type{T}, x::T) where {T<:FlagSet} = true
Base.isvalid(x::T) where {T<:FlagSet} = true
function Base.isvalid(::Type{T}, x::S) where {S,T<:FlagSet}
Base.isiterable(S) && all(elt ∈ flags(T) for elt ∈ x)
end
function Base.isvalid(::Type{T}, x::Symbol) where {T<:FlagSet{Symbol}}
x ∈ flags(T)
end
(::Type{I})(x::FlagSet) where {I<:Integer} = I(x.bitflags)::I
Base.cconvert(::Type{I}, x::FlagSet) where {I<:Integer} = I(x.bitflags)
Base.write(io::IO, x::T) where {T<:FlagSet} = write(io, x.bitflags)
Base.read(io::IO, ::Type{T}) where {T<:FlagSet} = T(BitMask(read(io, basetype(T))))
#Base.isless(x::FlagSet{T}, y::FlagSet{T}) where {T<:Integer} = isless(T(x), T(y))
Base.:|(x::T, y::T) where {T<:FlagSet} = T(BitMask(x.bitflags | y.bitflags))
Base.:&(x::T, y::T) where {T<:FlagSet} = T(BitMask(x.bitflags & y.bitflags))
Base.:⊻(x::T, y::T) where {T<:FlagSet} = T(BitMask(x.bitflags ⊻ y.bitflags))
Base.:~(x::T) where {T<:FlagSet} = setdiff(typemax(T), x)
Base.iszero(x::FlagSet) = isempty(x)
# Iterator interface
function Base.iterate(x::T, xi::Integer = x.bitflags) where {T<:FlagSet}
iszero(xi) && (return nothing)
fs = flagset_flags(T)
nbit = trailing_zeros(xi)
xi ⊻= typeof(xi)(1) << nbit
return (fs[nbit+1], xi)
end
Base.length(x::FlagSet) = count_ones(x.bitflags)
Base.isempty(x::FlagSet) = iszero(x.bitflags)
"""
flags(x::FlagSet)
Return the set of flags in `x` as a `Tuple`.
# Examples
```julia
julia> @symbol_flagset FontFlags bold=1 italic=2 large=4
julia> flags(FontFlags(3))
(:bold, :italic)
```
"""
flags(x::T) where {T<:FlagSet} = NTuple{length(x),eltype(T)}(x)
"""
flags(T)
Return the set of flags of type `T` as a `Tuple`.
# Examples
```julia
julia> @flagset RoundingFlags RoundDown RoundUp RoundNearest
julia> flags(RoundingFlags)
(RoundingMode{:Down}(), RoundingMode{:Up}(), RoundingMode{:Nearest}())
```
"""
flags(::Type{<:FlagSet})
# Set manipulation
Base.union(x::T, y::T) where {T<:FlagSet} = T(BitMask(x.bitflags | y.bitflags))
Base.intersect(x::T, y::T) where {T<:FlagSet} = T(BitMask(x.bitflags & y.bitflags))
Base.setdiff(x::T, y::T) where {T<:FlagSet} = T(BitMask(x.bitflags & ~y.bitflags))
Base.issubset(x::T, y::T) where {T<:FlagSet} = (x.bitflags & y.bitflags) == x.bitflags
Base.in(elt, x::T) where {T<:FlagSet} = !iszero(get_flag_bit(T, elt, zero(basetype(T))) & x.bitflags)
Base.:⊊(x::T, y::T) where {T<:FlagSet} = x != y && (x.bitflags & y.bitflags) == x.bitflags
Base.empty(s::FlagSet{B,F}, ::Type{F}) where {B,F} = typeof(s)()
Base.empty(s::FlagSet) = typeof(s)()
# Printing
function Base.show(io::IO, x::T) where {T<:FlagSet}
compact = get(io, :compact, false)::Bool
type_p = (get(io, :typeinfo, false) == T)::Bool
malformed = !isvalid(x)
if compact || malformed
xi = Integer(x)
type_p &= malformed
type_p || show(io, T)
type_p || print(io, "(")
show(io, xi)
type_p || print(io, malformed ? " #= Invalid code =#)" : ")")
else
show(io, T)
print(io, "([")
join(io, repr.(x), ", ")
print(io, "])")
end
end
function Base.show(io::IO, mime::MIME"text/plain", x::FlagSet)
if get(io, :compact, false)
show(io, x)
else
invoke(show, Tuple{typeof(io),typeof(mime),AbstractSet}, io, mime, x)
end
end
# Printing FlagSet type
function Base.show(io::IO, mime::MIME"text/plain", type::Type{<:FlagSet})
if isconcretetype(type) && !(get(io, :compact, false))
print(io, "FlagSet ")
Base.show_datatype(io, type)
print(io, ":")
keys = map(key -> isnothing(key) ? "" : String(key), flagkeys(type))
if !all(isempty, keys)
klen = maximum(length, keys)
keys = map(k -> isempty(k) ? ' '^(klen+2) : k * ' '^(klen-length(k)) * " = ", keys)
end
for (flag, key) ∈ zip(flags(type), keys)
bit = get_flag_bit(type, flag)
print(io, "\n ", key, repr(bit), " --> ", repr(flag))
end
else
invoke(show, Tuple{typeof(io),typeof(mime),Type}, io, mime, type)
end
end
function flagset_argument_error(typename, x)
throw(ArgumentError(string("invalid value for FlagSet $(typename): ", repr(x))))
end
function get_flag_bit(::Type{T}, flag, default) where {T<:FlagSet}
get(flag_bit_map(T), flag, default)
end
function get_flag_bit(::Type{T}, flag) where {T<:FlagSet}
not_found = basetype(T)(0x7f)
val = get(flag_bit_map(T), flag, not_found)
val == not_found && flagset_argument_error(T, flag)
val
end
# Default constructors
function (::Type{T})(flag::Symbol, flags::Symbol...) where {T<:FlagSet{Symbol}}
T((flag, flags...))
end
function (::Type{T})(itr) where {T<:FlagSet}
Base.isiterable(typeof(itr)) || flagset_argument_error(T, itr)
bitmask::basetype(T) = 0
for flag ∈ itr
bitmask |= get_flag_bit(T, flag)
end
T(BitMask(bitmask))
end
function (::Type{T})(bitmask::Integer) where {T<:FlagSet}
T(BitMask(bitmask))
end
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
|
[
"BSD-3-Clause",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | code | 16416 | # This file is part of FlagSets.jl project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.
"""
@symbol_flagset T[::BaseType] flag_1[=bit_1] flag_2[=bit_2] ...
Create a `FlagSet{Symbol,BaseType}` subtype with name `T` and the flags supplied.
Each instance of `T` represents a subset of `{:flag1, :flag2, ...}`.
The associated `bit_1`,`bit_2`, etc, if provided, must be distinct positive powers of 2.
The following constructors are provided:
- `T(itr)`: construct a set of the symbols from the given iterable object. Each symbol
must be one of :`flag_1`, :`flag_2`, etc;
- `T()`: construct an empty set;
- `T(sym1::Symbol, syms::Symbol...)`: equivalent to `T([sym1, syms...])`
- `T(bitmask::Integer)`: construct a set of flags associated with each bit in `mask`;
- `T(; kwargs...)`: each `flag_i` can be supplied as a boolean value
(`flag_i = true` includes `:flag_i`, `flag_i = false` excludes it).
It should be safe to new constructor methods and/or overriding the methods provided
(except the default using an internal struct, i.e., `T(::FlagSets.BitMask)`).
To construct sets of non-`Symbol` constants, use the macro [`@flagset`](@ref).
# Examples
```julia
julia> @symbol_flagset FontFlags bold=1 italic=2 large=4
julia> FontFlags(1)
FontFlags with 1 element:
:bold
julia> FontFlags(:bold, :italic)
FontFlags with 2 elements:
:bold
:italic
julia> FontFlags(bold=true, italic=false)
FontFlags with 1 element:
:bold
julia> for flag in FontFlags(3); println(flag) end
bold
italic
julia> FontFlags(3) | FontFlags(4)
FontFlags with 3 elements:
:bold
:italic
:large
julia> eltype(FontFlags)
Symbol
julia> typemax(FontFlags)
FontFlags with 3 elements:
:bold
:italic
:large
julia> typemin(FontFlags)
FontFlags([])
```
Values can also be specified inside a `begin` block, e.g.
```julia
@symbol_flagset T begin
flag_1 [= x]
flag_2 [= y]
end
```
If `BaseType` is provided, it must be an `Integer` type big enough to represent each
`bit_i`. Otherwise, some convenient integer type is inferred
(`UInt32` is used if possible, to guarantee compatibility with C code).
Each instance of `T` can be converted to `BaseType`, where each bit set in the
converted `BaseType` corresponds to a flag in the flag set. `read` and `write`
perform these conversions automatically. In case the flagset is created with a non-default
`BaseType`, `Integer(flagset)` will return the integer `flagset` with the type `BaseType`.
```julia
julia> convert(Int, FontFlags(bold=true, italic=false))
1
julia> convert(Integer, FontFlags(bold=true, italic=false))
0x00000001
```
To list flags of a flag set type or instance, use `flags`, e.g.
```julia
julia> flags(FontFlags)
(:bold, :italic, :large)
julia> flags(FontFlags(3))
(:bold, :italic)
```
"""
macro symbol_flagset(typespec::Union{Symbol,Expr}, flagspecs...)
expand_flagset(typespec, flagspecs, true, __module__)
end
"""
@flagset T [key_1 =] [bit_1 -->] flag_1 [key_2 =] [bit_2 -->] flag_2...
Create a [`FlagSet`](@ref) subtype with name `T` and the flags supplied (evaluated).
Each instance of the created type represents a subset of `{flag_1, flag_2, ...}`.
The associated `bit_1`,`bit_2`, etc, if provided, must be distinct positive powers of 2.
The following constructors are provided:
- `T(itr)`: construct a set of the flags from the given iterable object. Each flag
must be one of `flag_1`, `flag_2`, etc;
- `T()`: construct an empty set;
- `T(bitmask::Integer)`: construct a set of flags associated with each bit in `mask`;
- `T(; kwargs...)`: each `key_i` can be given as a keyword with boolean value
(`key_i = true` includes `flag_i`, `key_i = false` excludes it).
It should be safe to new constructor methods and/or overriding the methods provided
(except the default which is defined for the internal struct `FlagSets.BitMask`).
# Examples
```julia
julia> @flagset RoundingFlags begin
down = RoundDown
up = RoundUp
near = 16 --> RoundNearest
64 --> RoundNearestTiesUp # No key
end
julia> RoundingFlags([RoundDown,RoundUp])
RoundingFlags with 2 elements:
RoundingMode{:Down}()
RoundingMode{:Up}()
julia> RoundingFlags(near = true, up = false, RoundNearestTiesUp = true)
RoundingFlags with 2 elements:
RoundingMode{:Nearest}()
RoundingMode{:NearestTiesUp}()
julia> RoundingFlags(1)
RoundingFlags with 1 element:
RoundingMode{:Down}()
julia> for flag in RoundingFlags(3); println(flag) end
RoundingMode{:Down}()
RoundingMode{:Up}()
julia> RoundingFlags(3) | RoundingFlags(16)
RoundingFlags with 3 elements:
RoundingMode{:Down}()
RoundingMode{:Up}()
RoundingMode{:Nearest}()
julia> eltype(RoundingFlags)
RoundingMode
julia> typemax(RoundingFlags)
RoundingFlags with 4 elements:
RoundingMode{:Down}()
RoundingMode{:Up}()
RoundingMode{:Nearest}()
RoundingMode{:NearestTiesUp}()
julia> typemin(RoundingFlags)
RoundingFlags([])
```
If some `flag_i` is a `Symbol` and `key_i` is not explicitly given, `key_i` is set to
`flag_i`. Therefore, both macros below are equivalent:
```
@flagset FontFlags :bold :italic 8 --> :large
@flagset FontFlags begin
bold = :bold
italic = :italic
large = 8 --> :large
end
```
The following syntaxes can be used to provide `FlagType` and/or `BaseType`:
```julia
@flagset T {FlagType,BaseType} ... # Use supplied types
@flagset T {FlagType} ... # Detect BaseType
@flagset T {FlagType,_} ... # Detect BaseType too
@flagset T {_,BaseType} ... # Detect FlagType
@flagset T {} ... # Braces are ignored
```
If `FlagType` is not provided or is `_`, it is inferred from the flag values
(like array constructors do).
Otherwise, `flag_1`, `flag_2`, etc, must be of type `FlagType`.
If `BaseType` is not provided or is `_`, some convenient integer type is inferred
(`UInt32` is used if possible, for maximum compatibility with C code).
Otherwise, it must be an `Integer` type big enough to represent each `bit_i`.
Each instance of `T` can be converted to `BaseType`, where each bit set in the
converted `BaseType` corresponds to a flag in the flag set. `read` and `write`
perform these conversions automatically. In case the flagset is created with a non-default
`BaseType`, `Integer(flagset)` will return the integer `flagset` with the type `BaseType`.
```julia
julia> convert(Int, RoundingFlags(up = true, near = true))
6
julia> convert(Integer, RoundingFlags(up = true, near = true))
0x00000006
```
To list flags of a flag set type or instance, use `flags`, e.g.
```julia
julia> flags(RoundingFlags)
(RoundingMode{:Down}(), RoundingMode{:Up}(), RoundingMode{:Nearest}())
julia> flags(RoundingFlags(3))
(RoundingMode{:Down}(), RoundingMode{:Up}())
```
!!! note
For backward compatibility, the syntax `@flagset T::BaseType ...` is equivalent to
`@symbol_flagset T::BaseType ...`, but the former syntax deprecated
(use [`symbol_flagset`](@ref) instead).
"""
macro flagset(typespec::Union{Symbol,Expr}, flagspecs...)
try
return expand_flagset(typespec, flagspecs, false, __module__)
catch ex
throw(ex isa UndefVarError ? undef_var_error_hint(ex) : ex)
end
end
## Error creation
function undef_var_error_hint(ex)
ErrorException(
"An $ex has been caught during macroexpansion of @flagset. If you are using " *
"the old syntax (before version 0.3), use @symbol_flagset or the following syntax:" *
"\n @flagset T [bit_1 -->] :flag_1 [bit_2 -->] :flag_2 ..."
)
end
function deprecated_syntax_message(typename, BaseType)
ArgumentError(
"Deprecated syntax for macro @flagset. Use @symbol_flagset or use the syntax:" *
"\n @flagset $typename {Symbol,$BaseType)} [bit_1 -->] :flag_1 [bit_2 -->] :flag_2 ..."
)
end
function invalid_bit_error(typename, flagspec)
ArgumentError("invalid bit for FlagSet $typename: $flagspec; should be an integer positive power of 2")
end
function invalid_flagspec_error(typename, flagspec)
ArgumentError("invalid flag argument for FlagSet $typename: $flagspec")
end
function overflow_error(typename, flagspec)
ArgumentError("overflow in bit of flag $flagspec for FlagSet $typename")
end
function not_unique_error(field::Symbol, typename, value)
ArgumentError("$field for FlagSet $typename is not unique: $value")
end
function invalid_type_error(kind::Symbol, typename, type)
ArgumentError("invalid $kind type for FlagSet $typename: $type")
end
function check_flag_type(typename, FlagType)
(isnothing(FlagType) || FlagType isa Type) ||
throw(invalid_type_error(:flag, typename, FlagType))
end
function check_base_type(typename, BaseType)
(isnothing(BaseType) || BaseType isa Type && BaseType <: Integer) ||
throw(invalid_type_error(:base, typename, BaseType))
end
## Helper functions
function _to_nothing(expr, __module__)
expr == :_ ? nothing : Core.eval(__module__, expr)
end
function parse_flag_set_type(typespec, of_type, symflags::Bool, __module__)
BaseType = nothing
FlagType = symflags ? Symbol : nothing
typename = nothing
if !isnothing(of_type)
if typespec isa Symbol && 0 ≤ length(of_type.args) ≤ 2
typename = typespec
length(of_type.args) ≥ 1 && (FlagType = _to_nothing(of_type.args[1], __module__))
length(of_type.args) ≥ 2 && (BaseType = _to_nothing(of_type.args[2], __module__))
# else typename = nothing # indicate error
end
elseif (
isa(typespec, Expr) &&
typespec.head === :(::) &&
length(typespec.args) == 2 &&
isa(typespec.args[1], Symbol)
)
symflags || @warn(deprecated_syntax_message(typespec.args[1], typespec.args[2]), maxlog = 1)
FlagType = Symbol
typename = typespec.args[1]
BaseType = Core.eval(__module__, typespec.args[2])
elseif isa(typespec, Symbol)
typename = typespec
# else typename = nothing
end
if isnothing(typename)
throw(ArgumentError("invalid type expression for FlagSet: $typespec"))
end
check_flag_type(typename, FlagType)
check_base_type(typename, BaseType)
(typename, FlagType, BaseType, symflags)
end
function parse_flag_spec(typename, FlagType, flagspec, symflags::Bool, __module__)
key, flag, bit = nothing, nothing, nothing
if (
isa(flagspec, Expr) &&
(flagspec.head === :(=) || flagspec.head === :kw) &&
length(flagspec.args) == 2
)
key = flagspec.args[1]
flag_value = flagspec.args[2]
elseif FlagType == Symbol && flagspec isa Symbol
key = flag = flagspec
return (key, flag, nothing)
elseif symflags
flag_value = nothing # indicates an error
else
flag_value = flagspec
end
if (isa(flag_value, Expr) && (flag_value.head === :-->) && length(flag_value.args) == 2)
bit = Core.eval(__module__, flag_value.args[1]) # allow consts and exprs, e.g. uint128"1"
flag_expr = flag_value.args[2]
flag = Core.eval(__module__, flag_expr)
else
flag_expr = flag_value
val = Core.eval(__module__, flag_value)
flag, bit = FlagType == Symbol && !(val isa Symbol) ? (key, val) : (val, nothing)
end
if isnothing(key)
key = flag isa Symbol && Base.isidentifier(flag) && flag != :missing ? flag : nothing
end
if isnothing(flag_value) || !(key isa Union{Symbol,Nothing})
throw(invalid_flagspec_error(typename, flagspec))
end
if !isnothing(bit)
(bit isa Real && bit >= 1 && ispow2(bit)) || throw(invalid_bit_error(typename, flagspec))
end
(key, flag, bit)
end
function parse_flag_specs(typename, FlagType, BaseType, flagspecs, symflags::Bool, __module__)
if length(flagspecs) == 1 && flagspecs[1] isa Expr && flagspecs[1].head === :block
flagspecs = flagspecs[1].args
end
result = Any[]
bit = one(BaseType)
mask = zero(BaseType)
flags = Set([])
keys = Set([])
for flagspec in flagspecs
flagspec isa LineNumberNode && continue
(key, flag, next_bit) = parse_flag_spec(typename, FlagType, flagspec, symflags, __module__)
bit::BaseType = something(next_bit, bit)
bit <= zero(BaseType) && throw(overflow_error(typename, flagspec))
flag::FlagType = flag
(bit & mask) != 0 && throw(not_unique_error(:bit, typename, bit))
flag in flags && throw(not_unique_error(:flag, typename, flag))
key in keys && throw(not_unique_error(:key, typename, key))
push!(flags, flag)
isnothing(key) || push!(keys, key)
mask |= bit
index = trailing_zeros(bit) + 1
push!(result, (key, flag, bit, index))
bit <<= 1
end
(sort!(result, by = t -> t[4]), mask)
end
function infer_types(FlagType, BaseType, parsed, mask)
if isnothing(FlagType)
# Construct an array from flags and let Julia tell us what is the best flag type
FlagType = eltype(collect(p[2] for p ∈ parsed))
end
if isnothing(BaseType)
BaseType = if mask ≤ typemax(UInt32)
UInt32
elseif mask ≤ typemax(UInt64)
UInt64
elseif mask ≤ typemax(UInt128)
UInt128
else
BigInt
end
end
(FlagType, BaseType)
end
function expand_flagset(typespec, flagspecs, symflags::Bool, __module__)
of_type = nothing
if !isempty(flagspecs) && first(flagspecs) isa Expr && first(flagspecs).head == :braces
of_type = first(flagspecs)
flagspecs = flagspecs[2:end]
end
if isempty(flagspecs)
throw(ArgumentError("no arguments given for FlagSet $typespec"))
end
(typename, FlagType, BaseType, symflags) =
parse_flag_set_type(typespec, of_type, symflags, __module__)
FT = something(FlagType, Any)
BT = something(BaseType, BigInt)
parsed, mask = parse_flag_specs(typename, FT, BT, flagspecs, symflags, __module__)
(FlagType, BaseType) = infer_types(FlagType, BaseType, parsed, mask)
len = last(parsed)[4] # last index
key_vector = Vector{Union{Symbol,Nothing}}(undef, len)
fill!(key_vector, nothing) # Avoid undefined reference errors
flag_vector = Vector{Union{FlagType,Nothing}}(undef, len)
fill!(flag_vector, nothing) # Avoid undefined reference errors
indices = BaseType[]
flag_bit_map = Base.ImmutableDict{FlagType,BaseType}()
for (key, flag, bit, index) ∈ parsed
key::Union{Symbol,Nothing} = key
flag::FlagType = flag
bit::BaseType = bit
key_vector[index] = key
flag_vector[index] = flag
flag_bit_map = Base.ImmutableDict(flag_bit_map, flag => bit)
push!(indices, index)
end
flagset_flags = Tuple(flag_vector)
flags = Tuple(flag_vector[idx] for idx in indices)
keys = Tuple(key_vector[idx] for idx in indices)
keys_flags = ((key, flag) for (key, flag) ∈ zip(keys, flags) if !isnothing(key))
blk = quote
# flagset definition
Base.@__doc__(struct $(esc(typename)) <: FlagSet{$FlagType,$BaseType}
bitflags::$BaseType
function $(esc(typename))(bitmask::FlagSets.BitMask)
bitmask = bitmask.bitmask
bitmask & $(mask) == bitmask || flagset_argument_error($(esc(typename)), bitmask)
return new(convert($BaseType, bitmask))
end
end)
function $(esc(typename))(; $((Expr(:kw, :($key::Bool), false) for (key, _) ∈ keys_flags)...))
bitmask::$BaseType = zero($BaseType)
$((:($key && (bitmask |= $(flag_bit_map[flag]))) for (key, flag) ∈ keys_flags)...)
$(esc(typename))(FlagSets.BitMask(bitmask))
end
FlagSets.flagset_flags(::Type{$(esc(typename))}) = $(esc(flagset_flags))
FlagSets.flags(::Type{$(esc(typename))}) = $(esc(flags))
FlagSets.flag_bit_map(::Type{$(esc(typename))}) = $(esc(flag_bit_map))
FlagSets.flagkeys(::Type{$(esc(typename))}) =
$(keys === flags ? :(FlagSets.flags($(esc(typename)))) : esc(keys))
Base.typemin(x::Type{$(esc(typename))}) = $(esc(typename))(FlagSets.BitMask($(zero(BaseType))))
Base.typemax(x::Type{$(esc(typename))}) = $(esc(typename))(FlagSets.BitMask($mask))
end
push!(blk.args, :nothing)
blk.head = :toplevel
return blk
end
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
|
[
"BSD-3-Clause",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | code | 11944 | # This file is part of FlagSets.jl project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.
@enum MyFlagType Foo Bar Baz Quux
@testset "Basic operation" begin
# Inline definition
@flagset TFlag1 RoundDown RoundUp RoundNearest
@test Int(TFlag1([RoundDown])) == 1
@test Int(TFlag1([RoundUp])) == 2
@test Int(TFlag1([RoundNearest])) == 4
@test TFlag1(1) == TFlag1([RoundDown])
@test TFlag1(2) == TFlag1([RoundUp])
@test TFlag1(4) == TFlag1([RoundNearest])
@test flags(TFlag1) == (RoundDown, RoundUp, RoundNearest)
@test length(TFlag1([RoundDown, RoundUp])) == 2
@test !iszero(TFlag1([RoundUp, RoundNearest]))
@test iszero(TFlag1())
@test eltype(TFlag1) == RoundingMode
# Block definition
@flagset TFlag2 begin
down = RoundDown
up = RoundUp
near = RoundNearest
end
@test Int(TFlag2(down = true)) == 1
@test Int(TFlag2(up = true)) == 2
@test Int(TFlag2(near = true)) == 4
@test TFlag2(down = true, up = false, near = true) == TFlag2([RoundDown, RoundNearest])
@test length(TFlag2([RoundNearest])) == 1
@test !iszero(TFlag2([RoundNearest]))
@test iszero(TFlag2())
@test eltype(TFlag2) == RoundingMode
# Explicit numbering, inline
@flagset TFlag3 {_,_} down = 2 --> RoundDown RoundUp near = 16 --> RoundNearest
@test Int(TFlag3(down = true)) == 2
@test Int(TFlag3([RoundUp])) == 4
@test Int(TFlag3(near = true)) == 16
@test isempty(typemin(TFlag3))
@test Int(typemax(TFlag3)) == 22
@test length(typemax(TFlag3)) == 3
@test TFlag3(down = false, near = true) == TFlag3([RoundNearest])
@test flags(TFlag3) == (RoundDown, RoundUp, RoundNearest)
@test eltype(TFlag3) == RoundingMode
# Construct from enums
@flagset TFlag4 {} begin
foo = 2 --> Foo
bar = Bar
16 --> Baz
quux = 64 --> Quux
end
@test Int(TFlag4(foo = true)) == 2
@test Int(TFlag4([Bar])) == 4
@test Int(TFlag4([Baz])) == 16
@test isempty(typemin(TFlag4))
@test Int(typemax(TFlag4)) == 86
@test length(typemax(TFlag4)) == 4
@test TFlag4(foo = false, quux = true) == TFlag4([Quux])
@test flags(TFlag4) == (Foo, Bar, Baz, Quux)
@test eltype(TFlag4) == MyFlagType
# UInt128
@flagset TFlag4a a = UInt128(1) << 96 --> Foo b = UInt128(1) << 120 --> Bar
@test length([TFlag4a([Foo, Bar])...]) == 2
@test flags(TFlag4a([Foo, Bar])) === (Foo, Bar)
@test all(s1 === s2 for (s1, s2) ∈ zip(TFlag4a([Foo, Bar]), [Foo, Bar]))
# BigInt
@flagset TFlag4b a = big(1) << 160 --> Int b = big(1) << 192 --> Inf
@test length([TFlag4b([Int, Inf])...]) == 2
@test flags(TFlag4b([Int, Inf])) === (Int, Inf)
@test all(s1 === s2 for (s1, s2) ∈ zip(TFlag4b([Int, Inf]), [Int, Inf]))
end
@testset "Mask and set operations" begin
# Mask operations
@test TFlag1([RoundDown]) | TFlag1([RoundUp]) | TFlag1([RoundNearest]) ==
TFlag1([RoundDown, RoundUp, RoundNearest])
@test Int(TFlag1(7)) == 7
@test TFlag1(7) == TFlag1([RoundDown]) | TFlag1([RoundUp]) | TFlag1([RoundNearest])
@test TFlag1(7) & TFlag1([RoundDown]) == TFlag1([RoundDown])
@test TFlag1(7) ⊻ TFlag1([RoundDown]) == TFlag1([RoundUp, RoundNearest])
@test ~TFlag1([RoundDown]) == TFlag1([RoundUp, RoundNearest])
@test Int(TFlag1([RoundDown])) < Int(TFlag1([RoundUp])) < Int(TFlag1([RoundNearest]))
@test Int(TFlag1([RoundDown]) | TFlag1([RoundUp])) < Int(TFlag1([RoundNearest]))
# Set operations
@test TFlag1([RoundDown]) ∪ TFlag1([RoundUp]) ∪ TFlag1([RoundNearest]) ==
TFlag1([RoundDown, RoundUp, RoundNearest])
@test TFlag1(7) == TFlag1([RoundDown]) ∪ TFlag1([RoundUp]) ∪ TFlag1([RoundNearest])
@test TFlag1(7) ∩ TFlag1([RoundDown]) == TFlag1([RoundDown])
@test TFlag1(7) ⊻ TFlag1([RoundDown]) == TFlag1([RoundUp, RoundNearest])
@test setdiff(typemax(TFlag1), TFlag1([RoundDown])) == TFlag1([RoundUp, RoundNearest])
@test RoundDown ∈ TFlag1([RoundDown])
@test RoundDown ∉ TFlag1([RoundUp, RoundNearest])
@test TFlag1([RoundUp]) ⊊ TFlag1([RoundUp, RoundNearest])
@test TFlag1([RoundNearest]) ⊊ TFlag1([RoundUp, RoundNearest])
@test !(TFlag1([RoundUp, RoundNearest]) ⊊ TFlag1([RoundUp, RoundNearest]))
@test !(TFlag1([RoundDown, RoundUp]) ⊊ TFlag1([RoundUp, RoundNearest]))
end # testset
@testset "Type properties" begin
# Default integer typing and compatibility with @symbol_flagset
@flagset TFlag5 :flag5a :flag5b
@test eltype(TFlag5) == Symbol
@test TFlag5(flag5a = true) == TFlag5(:flag5a)
@test typeof(Integer(TFlag5(:flag5a))) == UInt32
@test typeof(TFlag5) == DataType
@test typeof(TFlag5(:flag5a)) <: TFlag5 <: FlagSet <: AbstractSet
@test isbitstype(Flag5)
@test isbits(TFlag5(:flag5a))
# Construct non-default and infer type
@flagset TFlag6 {_, UInt16} begin
foo = 2 --> Foo
bar = Bar
16 --> Baz
quux = 64 --> Quux
end
@test typeof(Integer(TFlag6(foo = true))) == UInt16
@test UInt8(TFlag6(foo = true)) === 0x02
@test UInt16(TFlag6([Bar])) === 0x0004
@test UInt128(TFlag6([Baz])) === 0x00000000000000000000000000000010
@test typeof(TFlag6()) <: TFlag6 <: FlagSet <: AbstractSet
# Explicit bits of non-default types
@flagset TFlag7 {Int128, UInt8} sixty_four = big"1" --> 64 one_hundred = UInt8(2) --> 100
@test Integer(TFlag7(sixty_four = true)) === UInt8(1)
@test Integer(TFlag7(one_hundred = true)) === UInt8(2)
@test eltype(TFlag7) == Int128
@test TFlag7([64]) == TFlag7(sixty_four = true)
@test TFlag7([100]) == TFlag7(one_hundred = true)
@test 1 ∉ TFlag7([64])
@test 64 ∈ TFlag7([64])
# Correctly detect base type
@flagset TFlag8 {} missing (Int64(1) << 60) --> nothing
@test eltype(TFlag8) == Union{Missing,Nothing}
@test typeof(Integer(TFlag8())) == UInt64
@test typeof(Int(TFlag8())) == Int
@flagset TFlag9 {Any,_} missing (Int128(1) << 120) --> nothing
@test eltype(TFlag9) == Any
@test typeof(Integer(TFlag9())) == UInt128
@test typeof(Int(TFlag9())) == Int
# UInt128 and BigInt
@test typeof(Integer(TFlag4a())) == UInt128
@test typeof(Integer(TFlag4b())) == BigInt
end # testset
@testset "Validate type" begin
@test isvalid(TFlag1([RoundDown]))
@test isvalid(TFlag1([RoundUp]))
@test isvalid(TFlag1(0x0000_0003))
@test !isvalid(TFlag1, UInt32(1 << 3))
@test !isvalid(TFlag1, UInt32(1 << 4))
@test !isvalid(TFlag1, UInt32(1 << 5 | 1))
@test !isvalid(TFlag1, UInt32(1 << 29 | 1 << 3))
@test isvalid(TFlag6(foo = true))
@test isvalid(TFlag6([Baz]))
@test isvalid(TFlag6(0x06))
@test !isvalid(TFlag6, UInt8(1 << 3))
@test !isvalid(TFlag6, UInt8(1 << 5))
@test !isvalid(TFlag6, UInt8(1 << 4 | 1))
@test !isvalid(TFlag6, UInt8(1 << 7 | 1 << 2))
@test isvalid(TFlag1, [RoundDown])
@test !isvalid(TFlag1, [RoundNearestTiesAway])
@test isvalid(TFlag1, [RoundDown, RoundUp])
@test isvalid(TFlag1, ([RoundDown, RoundUp]))
@test isvalid(TFlag1, Set([RoundDown, RoundUp]))
@test TFlag1(Set([RoundDown, RoundUp])) == TFlag1([RoundDown, RoundUp])
@test !isvalid(TFlag1, [:foo, :bar])
end
@testset "Error conditions" begin
@test_throws(
ArgumentError("no arguments given for FlagSet Foo"),
@macrocall(@flagset Foo),
)
@test_throws(
invalid_type_error(:base, :Foo, :Float64),
@macrocall(@flagset Foo {_, Float64} x = 1.0),
)
@test_throws(
invalid_type_error(:flag, :Foo, 1234),
@macrocall(@flagset Foo {1234} x = 1.0),
)
# Require uniqueness
@test_throws(
not_unique_error(:bit, :Foo, 1),
@macrocall(@flagset Foo x = 1 --> :x y = 1 --> :y),
)
@test_throws(
not_unique_error(:bit, :Foo, 2),
@macrocall(@flagset Foo x = 2 --> :x y = 2 --> :y),
)
# Explicit bits must be powers of two
@test_throws(
invalid_bit_error(:Foo, :(_three = 3 --> nothing)),
@macrocall(@flagset Foo _three = 3 --> nothing),
)
# Values must be integers
@test_throws(
invalid_bit_error(:Foo, :(_zero = "zero" --> nothing)),
@macrocall(@flagset Foo _zero = "zero" --> nothing),
)
@test_throws(
invalid_bit_error(:Foo, :('0' --> nothing)),
@macrocall(@flagset Foo '0' --> nothing),
)
@test_throws(
invalid_bit_error(:Foo, :(0.5 --> nothing)),
@macrocall(@flagset Foo 0.5 --> nothing),
)
# Names must be valid identifiers
@test_throws(
invalid_flagspec_error(:Foo, :(1 = 2)),
@macrocall(@flagset Foo 1 = 2),
)
# Disallow bit overflow
@test_throws(
overflow_error(:Foo, :(y = nothing)),
@macrocall(@flagset Foo {nothing, UInt32} x = UInt32(1) << 31 --> missing y = nothing),
)
end # testset
@testset "Input/Output" begin
@flagset TFlag10 {nothing, UInt64} foo = 1 --> Foo bar = 256 --> Bar
@flagset TFlag11 {nothing, UInt8} foo = 128 --> Foo bar = 2 --> Bar
let io = IOBuffer()
write(io, TFlag11([Foo, Bar]))
write(io, TFlag10(bar = true))
write(io, TFlag11([Foo]))
seekstart(io)
@test read(io, TFlag11) == TFlag11([Foo, Bar])
@test read(io, TFlag10) == TFlag10(bar = true)
@test read(io, TFlag11) == TFlag10([Foo])
end
let io = IOBuffer()
serialize(io, TFlag10([Foo]))
seekstart(io)
@test deserialize(io) === TFlag10([Foo])
end
end # testset
# In submodule and not imported to test prefix printing
module TSubModule
using ..FlagSets
@flagset TBits {Int, UInt8} 1 2 3 4
end
@testset "String representations" begin
@flagset TFilePerms {String, UInt8} 4 --> "READ" 2 --> "WRITE" 1 --> "EXEC"
@test string(TFilePerms) == "TFilePerms"
@test string(TSubModule.TBits) == "Main.TSubModule.TBits"
@test string(TFilePerms()) == "TFilePerms([])"
@test string(TSubModule.TBits([1])) == "Main.TSubModule.TBits([1])"
@test repr("text/plain", TFilePerms) ==
"FlagSet $(string(TFilePerms)):\n" *
" 0x01 --> \"EXEC\"\n" *
" 0x02 --> \"WRITE\"\n" *
" 0x04 --> \"READ\""
@test repr("text/plain", TSubModule.TBits) ==
"FlagSet Main.TSubModule.TBits:\n" *
" 0x01 --> 1\n" *
" 0x02 --> 2\n" *
" 0x04 --> 3\n" *
" 0x08 --> 4"
@test repr(TFilePerms(["EXEC"])) == "TFilePerms([\"EXEC\"])"
@test repr(TSubModule.TBits([1])) == "Main.TSubModule.TBits([1])"
@test repr(TFilePerms(["EXEC", "READ"])) == "TFilePerms([\"EXEC\", \"READ\"])"
@test repr(TSubModule.TBits([1, 4])) == "Main.TSubModule.TBits([1, 4])"
@test repr(TFilePerms() | TFilePerms(["READ"])) == "TFilePerms([\"READ\"])"
let io = IOBuffer(), ioc = IOContext(io, :compact => true, :module => Main)
show(io, MIME"text/plain"(), FlagSet)
@test String(take!(io)) == "FlagSet"
show(ioc, MIME"text/plain"(), FlagSet)
@test String(take!(io)) == "FlagSet"
# Explicit :compact --> false required for consistency across Julia versions
iof = IOContext(io, :compact => false, :module => Main)
show(iof, MIME"text/plain"(), Union{TFilePerms,TSubModule.TBits})
@test String(take!(io)) == "Union{TFilePerms, Main.TSubModule.TBits}"
show(ioc, MIME"text/plain"(), Union{TFilePerms,TSubModule.TBits})
@test String(take!(io)) == "Union{TFilePerms, TBits}"
show(ioc, TFilePerms())
@test String(take!(io)) == "TFilePerms(0x00)"
show(ioc, TSubModule.TBits([1]))
@test String(take!(io)) == "TBits(0x01)"
show(ioc, TFilePerms(["EXEC", "READ"]))
@test String(take!(io)) == "TFilePerms(0x05)"
show(ioc, TSubModule.TBits([1, 4]))
@test String(take!(io)) == "TBits(0x09)"
end
end # testset
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
|
[
"BSD-3-Clause",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | code | 1015 | # This file is part of FlagSets.jl project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.
using FlagSets
using Test, Serialization
using FlagSets: deprecated_syntax_message, undef_var_error_hint
using FlagSets: invalid_bit_error, invalid_flagspec_error, invalid_type_error
using FlagSets: overflow_error, not_unique_error
using FlagSets: BitMask
macro macrocall(ex)
@assert Meta.isexpr(ex, :macrocall)
ex.head = :call
for i = 2:length(ex.args)
ex.args[i] = QuoteNode(ex.args[i])
end
insert!(ex.args, 3, __module__)
return esc(ex)
end
if VERSION >= v"1.6"
@testset "FlagSets of symbols" verbose=true begin
include("symbol_flagsets.jl")
end
@testset "FlagSets of other types" verbose=true begin
include("flagset_type.jl")
end
else
@testset "FlagSets of symbols" begin
include("symbol_flagsets.jl")
end
@testset "FlagSets of other types" begin
include("flagset_type.jl")
end
end
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
|
[
"BSD-3-Clause",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | code | 11223 | # This file is part of FlagSets.jl project, which is licensed under BDS-3-Clause.
# See file LICENSE.md for more information.
@testset "Basic operation" begin
# Inline definition
@symbol_flagset Flag1 flag1a flag1b flag1c
@test Int(Flag1(:flag1a)) == 1
@test Int(Flag1(:flag1b)) == 2
@test Int(Flag1(:flag1c)) == 4
@test Flag1(1) == Flag1(:flag1a)
@test Flag1(2) == Flag1(:flag1b)
@test Flag1(4) == Flag1(:flag1c)
@test flags(Flag1) == (:flag1a, :flag1b, :flag1c)
@test Flag1(flag1a = true, flag1b = false, flag1c = true) == Flag1(:flag1a, :flag1c)
@test length(Flag1(:flag1a, :flag1c)) == 2
@test !iszero(Flag1(:flag1a, :flag1c))
@test iszero(Flag1())
# Block definition
@symbol_flagset Flag2 begin
flag2a
flag2b
flag2c
end
@test Int(Flag2(:flag2a)) == 1
@test Int(Flag2(:flag2b)) == 2
@test Int(Flag2(:flag2c)) == 4
@test Flag2(flag2a = true, flag2b = false, flag2c = true) == Flag2(:flag2a, :flag2c)
@test length(Flag2(:flag2b)) == 1
@test !iszero(Flag2(:flag2b))
@test iszero(Flag2())
# Explicit numbering, inline
@symbol_flagset Flag3 flag3a = 1 flag3b flag3c = 8
@test Int(Flag3(:flag3a)) == 1
@test Int(Flag3(:flag3b)) == 2
@test Int(Flag3(:flag3c)) == 8
@test isempty(typemin(Flag3))
@test Int(typemax(Flag3)) == 11
@test length(typemax(Flag3)) == 3
@test Flag3(flag3a = true, flag3b = false, flag3c = true) == Flag3(:flag3a, :flag3c)
@test flags(Flag3) == (:flag3a, :flag3b, :flag3c)
# UInt128
@symbol_flagset Flag4a::UInt128 a = UInt128(1) << 96 b = UInt128(1) << 120
@test length([Flag4a(:a, :b)...]) == 2
@test flags(Flag4a(:a, :b)) === (:a, :b)
@test all(s1 === s2 for (s1, s2) ∈ zip(Flag4a(:a, :b), [:a, :b]))
# BigInt
@symbol_flagset Flag4b::BigInt a = big(1) << 160 b = big(1) << 192
@test length([Flag4b(:a, :b)...]) == 2
@test flags(Flag4b(:a, :b)) === (:a, :b)
@test all(s1 === s2 for (s1, s2) ∈ zip(Flag4b(:a, :b), [:a, :b]))
end
@testset "Mask and set operations" begin
# Mask operations
@test Flag1(:flag1a) | Flag1(:flag1b) | Flag1(:flag1c) == Flag1(:flag1a, :flag1b, :flag1c)
@test Int(Flag1(7)) == 7
@test Flag1(7) == Flag1(:flag1a) | Flag1(:flag1b) | Flag1(:flag1c)
@test Flag1(7) & Flag1(:flag1a) == Flag1(:flag1a)
@test Flag1(7) ⊻ Flag1(:flag1a) == Flag1(:flag1b, :flag1c)
@test ~Flag1(:flag1a) == Flag1(:flag1b, :flag1c)
@test Int(Flag1(:flag1a)) < Int(Flag1(:flag1b)) < Int(Flag1(:flag1c))
@test Int(Flag1(:flag1a) | Flag1(:flag1b)) < Int(Flag1(:flag1c))
# Set operations
@test Flag1(:flag1a) ∪ Flag1(:flag1b) ∪ Flag1(:flag1c) == Flag1(:flag1a, :flag1b, :flag1c)
@test Flag1(7) == Flag1(:flag1a) ∪ Flag1(:flag1b) ∪ Flag1(:flag1c)
@test Flag1(7) ∩ Flag1(:flag1a) == Flag1(:flag1a)
@test Flag1(7) ⊻ Flag1(:flag1a) == Flag1(:flag1b, :flag1c)
@test setdiff(typemax(Flag1), Flag1(:flag1a)) == Flag1(:flag1b, :flag1c)
@test :flag1a ∈ Flag1(:flag1a)
@test :flag1a ∉ Flag1(:flag1b, :flag1c)
@test Flag1(:flag1b) ⊊ Flag1(:flag1b, :flag1c)
@test Flag1(:flag1c) ⊊ Flag1(:flag1b, :flag1c)
@test !(Flag1(:flag1b, :flag1c) ⊊ Flag1(:flag1b, :flag1c))
@test !(Flag1(:flag1a, :flag1b) ⊊ Flag1(:flag1b, :flag1c))
end # testset
# Julia errors when defining methods whithin nested testsets
@symbol_flagset Flag5 flag5a flag5b
@symbol_flagset Flag6::UInt8 flag6a flag6b flag6c
@symbol_flagset Flag7::UInt8 flag7a = big"1" flag7b = UInt8(2)
Flag5(::Integer) = typemax(Flag5)
Flag6(::Integer) = typemax(Flag6)
Flag7(::Integer) = typemax(Flag7)
@testset "Type properties" begin
# Default integer typing
@test typeof(Integer(Flag5(:flag5a))) == UInt32
@test typeof(Flag5) == DataType
@test typeof(Flag5(:flag5a)) <: Flag5 <: FlagSet <: AbstractSet
@test isbitstype(Flag5)
@test isbits(Flag5(:flag5a))
# Construct non-default
@test typeof(Integer(Flag6(:flag6a))) == UInt8
@test UInt8(Flag6(:flag6a)) === 0x01
@test UInt16(Flag6(:flag6b)) === 0x0002
@test UInt16(Flag6(BitMask(0x02))) === 0x0002
@test UInt16(Flag6([:flag6a, :flag6b])) === 0x0003
@test UInt128(Flag6(:flag6c)) === 0x00000000000000000000000000000004
# Explicit bits of non-default types
@test Integer(Flag7(:flag7a)) === UInt8(1)
@test Integer(Flag7(BitMask(1))) == UInt8(1)
@test Integer(Flag7(:flag7b)) === UInt8(2)
@test Integer(Flag7(BitMask(0x0000_0002))) === UInt8(2)
@test Integer(Flag7([:flag7a, :flag7b])) === UInt8(3)
@test Flag7(BitMask(0)) == typemin(Flag7)
# UInt128 and BigInt
@test typeof(Integer(Flag4a())) == UInt128
@test typeof(Integer(Flag4b())) == BigInt
end # testset
@testset "Validate type" begin
@test isvalid(Flag1(:flag1a))
@test isvalid(Flag1, Flag1(:flag1a))
@test isvalid(Flag1, :flag1a)
@test isvalid(Flag1(:flag1b))
@test isvalid(Flag1, :flag1b)
@test isvalid(Flag1, 0x0000_0003)
@test isvalid(Flag1, BitMask(0x0000_0003))
@test !isvalid(Flag1, UInt32(1 << 3))
@test !isvalid(Flag1, UInt32(1 << 4))
@test !isvalid(Flag1, UInt32(1 << 5 | 1))
@test !isvalid(Flag1, UInt32(1 << 29 | 1 << 3))
@test isvalid(Flag6, :flag6a)
@test isvalid(Flag6, :flag6b)
@test isvalid(Flag6, BitMask(0x03))
@test !isvalid(Flag6, UInt8(1 << 3))
@test !isvalid(Flag6, UInt8(1 << 4))
@test !isvalid(Flag6, UInt8(1 << 5 | 1))
@test !isvalid(Flag6, UInt8(1 << 7 | 1 << 3))
@test isvalid(Flag1, :flag1a)
@test !isvalid(Flag1, :foo)
@test isvalid(Flag1, [:flag1a, :flag1b])
@test isvalid(Flag1, (:flag1a, :flag1b))
@test isvalid(Flag1, Set([:flag1a, :flag1b]))
@test Flag1([:flag1a, :flag1b]) == Flag1(:flag1a, :flag1b)
@test Flag1((:flag1a, :flag1b)) == Flag1(:flag1a, :flag1b)
@test Flag1(Set([:flag1a, :flag1b])) == Flag1(:flag1a, :flag1b)
@test !isvalid(Flag1, [:foo, :bar])
end
@testset "Error conditions" begin
@test_throws(
ArgumentError("no arguments given for FlagSet Foo"),
@macrocall(@symbol_flagset Foo),
)
@test_throws(
invalid_type_error(:base, :Foo, :Float64),
@macrocall(@symbol_flagset Foo::Float64 x = 1.0),
)
@test_throws(
ArgumentError("invalid type expression for FlagSet: 1234 + 1"),
@macrocall(@symbol_flagset 1234 + 1 x = 1 y = 2),
)
@test_throws(
ArgumentError("invalid type expression for FlagSet: 1234::UInt"),
@macrocall(@symbol_flagset 1234::UInt x = 1 y = 2),
)
# Require uniqueness
@test_throws(
not_unique_error(:bit, :Foo, 1),
@macrocall(@symbol_flagset Foo x = 1 y = 1),
)
@test_throws(
not_unique_error(:bit, :Foo, 2),
@macrocall(@symbol_flagset Foo x = 2 y = 2),
)
# Explicit bits must be powers of two
@test_throws(
invalid_bit_error(:Foo, :(_three = 3)),
@macrocall(@symbol_flagset Foo _three = 3),
)
# Values must be integers
@test_throws(
invalid_bit_error(:Foo, :(_zero = "zero")),
@macrocall(@symbol_flagset Foo _zero = "zero"),
)
@test_throws(
invalid_bit_error(:Foo, :(_zero = '0')),
@macrocall(@symbol_flagset Foo _zero = '0'),
)
@test_throws(
invalid_bit_error(:Foo, :(_zero = 0.5)),
@macrocall(@symbol_flagset Foo _zero = 0.5),
)
# Names must be valid identifiers
@test_throws(
invalid_flagspec_error(:Foo, :(x ? 1 : 2)),
@macrocall(@symbol_flagset Foo x ? 1 : 2),
)
@test_throws(
invalid_flagspec_error(:Foo, :(1 = 2)),
@macrocall(@symbol_flagset Foo 1 = 2),
)
# Disallow bit overflow
@test_throws(
overflow_error(:Foo, :y),
@macrocall(@symbol_flagset Foo::UInt32 x = (UInt32(1) << 31) y),
)
# Deprecated messages
@test_logs(
(:warn, deprecated_syntax_message(:MyFlags,:UInt32)),
@macrocall(@flagset MyFlags::UInt32 x = 1 y = 2),
)
@test_throws(
undef_var_error_hint(UndefVarError(:x)),
@macrocall(@flagset MyFlags2 x)
)
end # testset
@testset "Input/Output" begin
@symbol_flagset Flag9::UInt64 flag9a = 1 flag9b = 256
@symbol_flagset Flag10::UInt8 flag10a = 128 flag10b = 2
let io = IOBuffer()
write(io, Flag10(:flag10a, :flag10b))
write(io, Flag9(:flag9b))
write(io, Flag10(:flag10a))
write(io, Flag6(BitMask(2)))
seekstart(io)
@test read(io, Flag10) == Flag10(:flag10a, :flag10b)
@test read(io, Flag9) == Flag9(:flag9b)
@test read(io, Flag10) == Flag10(:flag10a)
@test read(io, Flag6) == Flag6(BitMask(2))
end
let io = IOBuffer()
serialize(io, Flag9(:flag9a))
seekstart(io)
@test deserialize(io) === Flag9(:flag9a)
end
end # testset
# In submodule and not imported to test prefix printing
module SubModule
using ..FlagSets
@symbol_flagset Bits::UInt8 one two four eight
end
@testset "String representations" begin
@symbol_flagset FilePerms::UInt8 READ = 4 WRITE = 2 EXEC = 1
@test string(FilePerms) == "FilePerms"
@test string(SubModule.Bits) == "Main.SubModule.Bits"
@test string(FilePerms()) == "FilePerms([])"
@test string(SubModule.Bits(:one)) == "Main.SubModule.Bits([:one])"
@test repr("text/plain", FilePerms) ==
"FlagSet $(string(FilePerms)):\n" *
" EXEC = 0x01 --> :EXEC\n" *
" WRITE = 0x02 --> :WRITE\n" *
" READ = 0x04 --> :READ"
@test repr("text/plain", SubModule.Bits) ==
"FlagSet Main.SubModule.Bits:\n" *
" one = 0x01 --> :one\n" *
" two = 0x02 --> :two\n" *
" four = 0x04 --> :four\n" *
" eight = 0x08 --> :eight"
@test repr(FilePerms(:EXEC)) == "FilePerms([:EXEC])"
@test repr(SubModule.Bits(:one)) == "Main.SubModule.Bits([:one])"
@test repr(FilePerms(:EXEC, :READ)) == "FilePerms([:EXEC, :READ])"
@test repr(SubModule.Bits(:one, :eight)) == "Main.SubModule.Bits([:one, :eight])"
@test repr(FilePerms() | FilePerms(:READ)) == "FilePerms([:READ])"
let io = IOBuffer(), ioc = IOContext(io, :compact => true, :module => Main)
show(io, MIME"text/plain"(), FlagSet)
@test String(take!(io)) == "FlagSet"
show(ioc, MIME"text/plain"(), FlagSet)
@test String(take!(io)) == "FlagSet"
# Explicit :compact => false required for consistency across Julia versions
iof = IOContext(io, :compact => false, :module => Main)
show(iof, MIME"text/plain"(), Union{FilePerms,SubModule.Bits})
@test String(take!(io)) == "Union{FilePerms, Main.SubModule.Bits}"
show(ioc, MIME"text/plain"(), Union{FilePerms,SubModule.Bits})
@test String(take!(io)) == "Union{FilePerms, Bits}"
show(ioc, FilePerms())
@test String(take!(io)) == "FilePerms(0x00)"
show(ioc, SubModule.Bits(:one))
@test String(take!(io)) == "Bits(0x01)"
show(ioc, FilePerms(:EXEC, :READ))
@test String(take!(io)) == "FilePerms(0x05)"
show(ioc, SubModule.Bits(:one, :eight))
@test String(take!(io)) == "Bits(0x09)"
end
end # testset
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.