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
|
---|---|---|---|---|---|---|---|---|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 7949 | struct AllConfigs{K} end
largest_k(::AllConfigs{K}) where K = K
struct SingleConfig end
"""
backward_tropical!(mode, ixs, xs, iy, y, ymask, size_dict)
The backward rule for tropical einsum.
* `mode` can be one of `:all` and `:single`,
* `ixs` and `xs` are labels and tensor data for input tensors,
* `iy` and `y` are labels and tensor data for the output tensor,
* `ymask` is the boolean mask for gradients,
* `size_dict` is a key-value map from tensor label to dimension size.
"""
function backward_tropical!(mode, ixs, @nospecialize(xs::Tuple), iy, @nospecialize(y), @nospecialize(ymask), size_dict)
# remove float to improve the stability of the algorithm
removeinf(x::CountingTropical{<:AbstractFloat}) = isinf(x.n) ? typeof(x)(prevfloat(x.n), x.c) : x
removeinf(x::Tropical{<:AbstractFloat}) = isinf(x.n) ? typeof(x)(prevfloat(x.n)) : x
removeinf(x) = x
y .= removeinf.(inv.(y) .* ymask)
masks = []
for i=1:length(ixs)
nixs = OMEinsum._insertat(ixs, i, iy)
nxs = OMEinsum._insertat( xs, i, y)
niy = ixs[i]
if mode isa AllConfigs
mask = zeros(Bool, size(xs[i]))
# here, we set a threshold `1e-12` to avoid round off errors.
mask .= inv.(einsum(EinCode(nixs, niy), nxs, size_dict)) .<= xs[i] .* Tropical(largest_k(mode)-1+1e-12)
push!(masks, mask)
elseif mode isa SingleConfig
A = einsum(EinCode(nixs, niy), nxs, size_dict)
push!(masks, onehotmask!(A, xs[i]))
else
error("unkown mode: $mod")
end
end
return masks
end
# one of the entry in `A` that equal to the corresponding entry in `X` is masked to true.
function onehotmask!(A::AbstractArray{T}, X::AbstractArray{T}) where T
@assert length(A) == length(X)
mask = falses(size(A)...)
found = false
@inbounds for j=1:length(A)
if X[j] ≈ inv(A[j]) && !found
mask[j] = true
found = true
else
X[j] = zero(T)
end
end
return mask
end
# the data structure storing intermediate `NestedEinsum` contraction results.
struct CacheTree{T}
content::AbstractArray{T}
siblings::Vector{CacheTree{T}}
end
function cached_einsum(se::SlicedEinsum, @nospecialize(xs), size_dict)
if length(se.slicing) != 0
@warn "Slicing is not supported for caching, got nslices = $(length(se.slicing))! Fallback to `NestedEinsum`."
end
return cached_einsum(se.eins, xs, size_dict)
end
function cached_einsum(code::NestedEinsum, @nospecialize(xs), size_dict)
if OMEinsum.isleaf(code)
y = xs[OMEinsum.tensorindex(code)]
return CacheTree(y, CacheTree{eltype(y)}[])
else
caches = [cached_einsum(arg, xs, size_dict) for arg in OMEinsum.siblings(code)]
y = einsum(OMEinsum.rootcode(code), ntuple(i->caches[i].content, length(caches)), size_dict)
return CacheTree(y, caches)
end
end
# computed mask tree by back propagation
function generate_masktree(mode, se::SlicedEinsum, cache, mask, size_dict)
if length(se.slicing) != 0
@warn "Slicing is not supported for generating masked tree! Fallback to `NestedEinsum`."
end
return generate_masktree(mode, se.eins, cache, mask, size_dict)
end
function generate_masktree(mode, code::NestedEinsum, cache, mask, size_dict)
if OMEinsum.isleaf(code)
return CacheTree(mask, CacheTree{Bool}[])
else
eins = OMEinsum.rootcode(code)
submasks = backward_tropical!(mode, getixs(eins), (getfield.(cache.siblings, :content)...,), OMEinsum.getiy(eins), cache.content, mask, size_dict)
return CacheTree(mask, generate_masktree.(Ref(mode), OMEinsum.siblings(code), cache.siblings, submasks, Ref(size_dict)))
end
end
# The masked einsum contraction
function masked_einsum(se::SlicedEinsum, @nospecialize(xs), masks, size_dict)
if length(se.slicing) != 0
@warn "Slicing is not supported for masked contraction! Fallback to `NestedEinsum`."
end
return masked_einsum(se.eins, xs, masks, size_dict)
end
function masked_einsum(code::NestedEinsum, @nospecialize(xs), masks, size_dict)
if OMEinsum.isleaf(code)
y = copy(xs[OMEinsum.tensorindex(code)])
y[OMEinsum.asarray(.!masks.content)] .= Ref(zero(eltype(y)))
return y
else
xs = [masked_einsum(arg, xs, mask, size_dict) for (arg, mask) in zip(OMEinsum.siblings(code), masks.siblings)]
y = einsum(OMEinsum.rootcode(code), (xs...,), size_dict)
y[OMEinsum.asarray(.!masks.content)] .= Ref(zero(eltype(y)))
return y
end
end
"""
bounding_contract(mode, code, xsa, ymask, xsb; size_info=nothing)
Contraction method with bounding.
* `mode` is a `AllConfigs{K}` instance, where `MIS-K+1` is the largest IS size that you care about.
* `xsa` are input tensors for bounding, e.g. tropical tensors,
* `xsb` are input tensors for computing, e.g. tensors elements are counting tropical with set algebra,
* `ymask` is the initial gradient mask for the output tensor.
"""
function bounding_contract(mode::AllConfigs, code::EinCode, @nospecialize(xsa), ymask, @nospecialize(xsb); size_info=nothing)
LT = OMEinsum.labeltype(code)
bounding_contract(mode, DynamicNestedEinsum(DynamicNestedEinsum{LT}.(1:length(xsa)), code), xsa, ymask, xsb; size_info=size_info)
end
function bounding_contract(mode::AllConfigs, code::Union{NestedEinsum,SlicedEinsum}, @nospecialize(xsa), ymask, @nospecialize(xsb); size_info=nothing)
size_dict = size_info===nothing ? Dict{OMEinsum.labeltype(code),Int}() : copy(size_info)
OMEinsum.get_size_dict!(code, xsa, size_dict)
# compute intermediate tensors
@debug "caching einsum..."
c = cached_einsum(code, xsa, size_dict)
# compute masks from cached tensors
@debug "generating masked tree..."
mt = generate_masktree(mode, code, c, ymask, size_dict)
# compute results with masks
masked_einsum(code, xsb, mt, size_dict)
end
# get the optimal solution with automatic differentiation.
function solution_ad(code::EinCode, @nospecialize(xsa), ymask; size_info=nothing)
LT = OMEinsum.labeltype(code)
solution_ad(DynamicNestedEinsum(DynamicNestedEinsum{LT}.(1:length(xsa)), code), xsa, ymask; size_info=size_info)
end
function solution_ad(code::Union{NestedEinsum,SlicedEinsum}, @nospecialize(xsa), ymask; size_info=nothing)
size_dict = size_info===nothing ? Dict{OMEinsum.labeltype(code),Int}() : copy(size_info)
OMEinsum.get_size_dict!(code, xsa, size_dict)
# compute intermediate tensors
@debug "caching einsum..."
c = cached_einsum(code, xsa, size_dict)
n = asscalar(c.content)
# compute masks from cached tensors
@debug "generating masked tree..."
mt = generate_masktree(SingleConfig(), code, c, ymask, size_dict)
config = read_config!(code, mt, Dict())
if length(config) !== length(labels(code)) # equal to the # of degree of freedoms
error("configuration `$(config)` is not fully determined!")
end
n, config
end
# get the solution configuration from gradients.
function read_config!(code::SlicedEinsum, mt, out)
read_config!(code.eins, mt, out)
end
function read_config!(code::NestedEinsum, mt, out)
for (arg, ix, sibling) in zip(OMEinsum.siblings(code), getixs(OMEinsum.rootcode(code)), mt.siblings)
if OMEinsum.isleaf(arg)
mask = convert(Array, sibling.content) # note: the content can be CuArray
for ci in CartesianIndices(mask)
if mask[ci]
for k in 1:ndims(mask)
if haskey(out, ix[k])
@assert out[ix[k]] == ci.I[k] - 1
else
out[ix[k]] = ci.I[k] - 1
end
end
end
end
else # nested
read_config!(arg, sibling, out)
end
end
return out
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 5368 | function config_type(::Type{T}, n, nflavor; all::Bool, tree_storage::Bool) where T
if all
if tree_storage
return treeset_type(T, n, nflavor)
else
return set_type(T, n, nflavor)
end
else
return sampler_type(T, n, nflavor)
end
end
"""
best_solutions(problem; all=false, usecuda=false, invert=false, tree_storage::Bool=false)
Find optimal solutions with bounding.
* When `all` is true, the program will use set for enumerate all possible solutions, otherwise, it will return one solution for each size.
* `usecuda` can not be true if you want to use set to enumerate all possible solutions.
* If `invert` is true, find the minimum.
* If `tree_storage` is true, use [`SumProductTree`](@ref) as the storage of solutions.
"""
function best_solutions(gp::GenericTensorNetwork; all=false, usecuda=false, invert=false, tree_storage::Bool=false, T=Float64)
if all && usecuda
throw(ArgumentError("ConfigEnumerator can not be computed on GPU!"))
end
xst = generate_tensors(_x(Tropical{T}; invert), gp)
ymask = trues(fill(nflavor(gp), length(getiyv(gp.code)))...)
if usecuda
xst = togpu.(xst)
ymask = togpu(ymask)
end
if all
# we use `Float64` as default because we want to support weighted graphs.
T = config_type(CountingTropical{T,T}, length(labels(gp)), nflavor(gp); all, tree_storage)
xs = generate_tensors(_x(T; invert), gp)
ret = bounding_contract(AllConfigs{1}(), gp.code, xst, ymask, xs)
return invert ? asarray(post_invert_exponent.(ret), ret) : ret
else
@assert ndims(ymask) == 0
t, res = solution_ad(gp.code, xst, ymask)
ret = fill(CountingTropical(asscalar(t).n, ConfigSampler(StaticBitVector(map(l->res[l], 1:length(res))))))
return invert ? asarray(post_invert_exponent.(ret), ret) : ret
end
end
"""
solutions(problem, basetype; all, usecuda=false, invert=false, tree_storage::Bool=false)
General routine to find solutions without bounding,
* `basetype` can be a type with counting field,
* `CountingTropical{Float64,Float64}` for finding optimal solutions,
* `Polynomial{Float64, :x}` for enumerating all solutions,
* `Max2Poly{Float64,Float64}` for optimal and suboptimal solutions.
* When `all` is true, the program will use set for enumerate all possible solutions, otherwise, it will return one solution for each size.
* `usecuda` can not be true if you want to use set to enumerate all possible solutions.
* If `tree_storage` is true, use [`SumProductTree`](@ref) as the storage of solutions.
"""
function solutions(gp::GenericTensorNetwork, ::Type{BT}; all::Bool, usecuda::Bool=false, invert::Bool=false, tree_storage::Bool=false) where BT
if all && usecuda
throw(ArgumentError("ConfigEnumerator can not be computed on GPU!"))
end
T = config_type(BT, length(labels(gp)), nflavor(gp); all, tree_storage)
ret = contractx(gp, _x(T; invert); usecuda=usecuda)
return invert ? asarray(post_invert_exponent.(ret), ret) : ret
end
"""
best2_solutions(problem; all=true, usecuda=false, invert=false, tree_storage::Bool=false)
Finding optimal and suboptimal solutions.
"""
best2_solutions(gp::GenericTensorNetwork; all=true, usecuda=false, invert::Bool=false, T=Float64) = solutions(gp, Max2Poly{T,T}; all, usecuda, invert)
function bestk_solutions(gp::GenericTensorNetwork, k::Int; invert::Bool=false, tree_storage::Bool=false, T=Float64)
xst = generate_tensors(_x(Tropical{T}; invert), gp)
ymask = trues(fill(2, length(getiyv(gp.code)))...)
T = config_type(TruncatedPoly{k,T,T}, length(labels(gp)), nflavor(gp); all=true, tree_storage)
xs = generate_tensors(_x(T; invert), gp)
ret = bounding_contract(AllConfigs{k}(), gp.code, xst, ymask, xs)
return invert ? asarray(post_invert_exponent.(ret), ret) : ret
end
"""
all_solutions(problem)
Finding all solutions grouped by size.
e.g. when the problem is [`MaximalIS`](@ref), it computes all maximal independent sets, or the maximal cliques of it complement.
"""
all_solutions(gp::GenericTensorNetwork; T=Float64) = solutions(gp, Polynomial{T,:x}, all=true, usecuda=false, tree_storage=false)
# NOTE: do we have more efficient way to compute it?
# NOTE: doing pair-wise Hamming distance might be biased?
"""
hamming_distribution(S, T)
Compute the distribution of pair-wise Hamming distances, which is defined as:
```math
c(k) := \\sum_{\\sigma\\in S, \\tau\\in T} \\delta({\\rm dist}(\\sigma, \\tau), k)
```
where ``\\delta`` is a function that returns 1 if two arguments are equivalent, 0 otherwise,
``{\\rm dist}`` is the Hamming distance function.
Returns the counting as a vector.
"""
function hamming_distribution(t1::ConfigEnumerator, t2::ConfigEnumerator)
return hamming_distribution(t1.data, t2.data)
end
function hamming_distribution(s1::AbstractVector{StaticElementVector{N,S,C}}, s2::AbstractVector{StaticElementVector{N,S,C}}) where {N,S,C}
return hamming_distribution!(zeros(Int, N+1), s1, s2)
end
function hamming_distribution!(out::AbstractVector, s1::AbstractVector{StaticElementVector{N,S,C}}, s2::AbstractVector{StaticElementVector{N,S,C}}) where {N,S,C}
@assert length(out) == N+1
@inbounds for a in s1, b in s2
out[hamming_distance(a, b)+1] += 1
end
return out
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 270 | @deprecate Independence(args...; kwargs...) IndependentSet(args...; kwargs...)
@deprecate MaximalIndependence(args...; kwargs...) MaximalIS(args...; kwargs...)
@deprecate NoWeight() UnitWeight()
@deprecate HyperSpinGlass(args...; kwargs...) SpinGlass(args...; kwargs...) | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 4146 | """
save_configs(filename, data::ConfigEnumerator; format=:binary)
Save configurations `data` to file `filename`. The format is `:binary` or `:text`.
"""
function save_configs(filename, data::ConfigEnumerator{N,S,C}; format::Symbol=:binary) where {N,S,C}
if format == :binary
write(filename, raw_matrix(data))
elseif format == :text
writedlm(filename, plain_matrix(data))
else
error("format must be `:binary` or `:text`, got `:$format`")
end
end
"""
load_configs(filename; format=:binary, bitlength=nothing, nflavors=2)
Load configurations from file `filename`. The format is `:binary` or `:text`.
If the format is `:binary`, the bitstring length `bitlength` must be specified,
`nflavors` specifies the degree of freedom.
"""
function load_configs(filename; bitlength=nothing, format::Symbol=:binary, nflavors=2)
if format == :binary
bitlength === nothing && error("you need to specify `bitlength` for reading configurations from binary files.")
S = ceil(Int, log2(nflavors))
C = _nints(bitlength, S)
return _from_raw_matrix(StaticElementVector{bitlength,S,C}, reshape(reinterpret(UInt64, read(filename)),C,:))
elseif format == :text
return from_plain_matrix(readdlm(filename); nflavors=nflavors)
else
error("format must be `:binary` or `:text`, got `:$format`")
end
end
function raw_matrix(x::ConfigEnumerator{N,S,C}) where {N,S,C}
m = zeros(UInt64, C, length(x))
@inbounds for i=1:length(x), j=1:C
m[j,i] = x.data[i].data[j]
end
return m
end
function plain_matrix(x::ConfigEnumerator{N,S,C}) where {N,S,C}
m = zeros(UInt8, N, length(x))
@inbounds for i=1:length(x), j=1:N
m[j,i] = x.data[i][j]
end
return m
end
function from_raw_matrix(m; bitlength, nflavors=2)
S = ceil(Int,log2(nflavors))
C = size(m, 1)
T = StaticElementVector{bitlength,S,C}
@assert bitlength*S <= C*64
_from_raw_matrix(T, m)
end
function _from_raw_matrix(::Type{StaticElementVector{N,S,C}}, m::AbstractMatrix) where {N,S,C}
data = zeros(StaticElementVector{N,S,C}, size(m, 2))
@inbounds for i=1:size(m, 2)
data[i] = StaticElementVector{N,S,C}(NTuple{C,UInt64}(view(m,:,i)))
end
return ConfigEnumerator(data)
end
function from_plain_matrix(m::Matrix; nflavors=2)
S = ceil(Int,log2(nflavors))
N = size(m, 1)
C = _nints(N, S)
T = StaticElementVector{N,S,C}
_from_plain_matrix(T, m)
end
function _from_plain_matrix(::Type{StaticElementVector{N,S,C}}, m::AbstractMatrix) where {N,S,C}
data = zeros(StaticElementVector{N,S,C}, size(m, 2))
@inbounds for i=1:size(m, 2)
data[i] = convert(StaticElementVector{N,S,C}, view(m, :, i))
end
return ConfigEnumerator(data)
end
# convert to Matrix
Base.Matrix(ce::ConfigEnumerator) = plain_matrix(ce)
Base.Vector(ce::StaticElementVector) = collect(ce)
########## saving tree ####################
"""
save_sumproduct(filename, t::SumProductTree)
Serialize a sum-product tree into a file.
"""
save_sumproduct(filename::String, t::SumProductTree) = serialize(filename, dict_serialize_tree!(t, Dict{UInt,Any}()))
"""
load_sumproduct(filename)
Deserialize a sum-product tree from a file.
"""
load_sumproduct(filename::String) = dict_deserialize_tree(deserialize(filename)...)
function dict_serialize_tree!(t::SumProductTree, d::Dict)
id = objectid(t)
if !haskey(d, id)
if t.tag === GenericTensorNetworks.LEAF || t.tag === GenericTensorNetworks.ZERO || t.tag == GenericTensorNetworks.ONE
d[id] = t
else
d[id] = (t.tag, objectid(t.left), objectid(t.right))
dict_serialize_tree!(t.left, d)
dict_serialize_tree!(t.right, d)
end
end
return id, d
end
function dict_deserialize_tree(id::UInt, d::Dict)
@assert haskey(d, id)
content = d[id]
if content isa SumProductTree
return content
else
(tag, left, right) = content
t = SumProductTree(tag, dict_deserialize_tree(left, d), dict_deserialize_tree(right, d))
d[id] = t
return t
end
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 4358 | """
graph_polynomial(problem, method; usecuda=false, T=Float64, kwargs...)
Computing the graph polynomial for specific problem.
Positional Arguments
----------------------------------
* `problem` can be one of the following instances,
* `IndependentSet` for the independence polynomial,
* `MaximalIS` for the maximal independence polynomial,
* `Matching` for the matching polynomial,
* `method` can be one of the following inputs,
* `Val(:finitefield)`, compute exactly with the finite field method.
It consumes additional kwargs [`max_iter`, `maxorder`], where `maxorder` is maximum order of polynomial
and `max_iter` is the maximum number of primes numbers to use in the finitefield algebra.
`max_iter` can be determined automatically in most cases.
* `Val(:polynomial)`, compute directly with `Polynomial` number type,
* `Val(:fft)`, compute with the fast fourier transformation approach, fast but needs to tune the hyperparameter `r`.
It Consumes additional kwargs [`maxorder`, `r`]. The larger `r` is,
the more accurate the factors of high order terms, and the less accurate the factors of low order terms.
* `Val(:fitting)`, compute with the polynomial fitting approach, fast but inaccurate for large graphs.
Keyword Arguments
----------------------------------
* `usecuda` is true if one wants to compute with CUDA arrays,
* `T` is the base type
"""
function graph_polynomial end
function graph_polynomial(gp::GenericTensorNetwork, ::Val{:fft}; usecuda=false, T=Float64,
maxorder=max_size(gp; usecuda=usecuda), r=1.0)
ω = exp(-2im*π/(maxorder+1))
xs = r .* collect(ω .^ (0:maxorder))
ys = [Array(contractx(gp, Complex{T}(x); usecuda=usecuda)) for x in xs]
map(ci->Polynomial(ifft(getindex.(ys, Ref(ci))) ./ (r .^ (0:maxorder))), CartesianIndices(ys[1]))
end
function graph_polynomial(gp::GenericTensorNetwork, ::Val{:fitting}; usecuda=false, T=Float64,
maxorder = max_size(gp; usecuda=usecuda))
xs = (0:maxorder)
ys = [Array(contractx(gp, T(x); usecuda=usecuda)) for x in xs]
map(ci->fit(xs, getindex.(ys, Ref(ci))), CartesianIndices(ys[1]))
end
function graph_polynomial(gp::GenericTensorNetwork, ::Val{:polynomial}; usecuda=false, T=Float64)
@assert !usecuda "Polynomial type can not be computed on GPU!"
contractx(gp::GenericTensorNetwork, Polynomial(T[0, 1]))
end
function graph_polynomial(gp::GenericTensorNetwork, ::Val{:laurent}; usecuda=false, T=Float64)
@assert !usecuda "Polynomial type can not be computed on GPU!"
contractx(gp::GenericTensorNetwork, LaurentPolynomial(T[1], 1))
end
function _polynomial_fit(f, ::Type{T}; maxorder) where T
xs = 0:maxorder
ys = [f(T(x)) for x in xs] # download to CPU
res = fill(T[], size(ys[1])) # contraction result can be a tensor
for ci in 1:length(ys[1])
A = zeros(T, maxorder+1, maxorder+1)
for j=1:maxorder+1, i=1:maxorder+1
A[j,i] = T(xs[j])^(i-1)
end
res[ci] = A \ T.(getindex.(ys, Ref(ci)))
end
return res
end
# T is not used in finitefield approach
function graph_polynomial(gp::GenericTensorNetwork, ::Val{:finitefield}; usecuda=false, T=BigInt,
maxorder=max_size(gp; usecuda), max_iter=100)
f = T->_polynomial_fit(x->Array(contractx(gp, x; usecuda)), T; maxorder)
return map(Polynomial, big_integer_solve(f, Int32, max_iter))
end
function big_integer_solve(f, ::Type{TI}, max_iter::Int=100) where TI
N = typemax(TI)
local res, respre, YS
for k = 1:max_iter
N = prevprime(N-TI(1))
@debug "iteration $k, computing on GP($(N)) ..."
T = Mods.Mod{N,TI}
rk = f(T)
if max_iter==1
return map(x->BigInt.(Mods.value.(x)), rk) # needs test
end
if k != 1
push!.(YS, rk)
res = map(x->improved_counting(x...), YS)
all(respre .== res) && return res
respre = res
else # k=1
YS = reshape([Any[] for i=1:length(rk)], size(rk))
push!.(YS, rk)
respre = map(x->BigInt.(value.(x)), rk)
end
end
@warn "result is potentially inconsistent."
return res
end
function improved_counting(ys::AbstractArray...)
map(yi->improved_counting(yi...), zip(ys...))
end
improved_counting(ys::Mod...) = Mods.CRT(ys...)
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2441 | """
random_square_lattice_graph(m::Int, n::Int, ρ::Real)
Create a random masked square lattice graph, with number of vertices fixed to ``\\lfloor mn\\rho \\rceil``.
"""
function random_square_lattice_graph(m::Int, n::Int, ρ::Real)
@assert ρ >=0 && ρ <= 1
square_lattice_graph(generate_mask(m, n, round(Int,m*n*ρ)))
end
"""
square_lattice_graph(mask::AbstractMatrix{Bool})
Create a masked square lattice graph.
"""
function square_lattice_graph(mask::AbstractMatrix{Bool})
locs = [(i, j) for i=1:size(mask, 1), j=1:size(mask, 2) if mask[i,j]]
unit_disk_graph(locs, 1.1)
end
"""
random_diagonal_coupled_graph(m::Int, n::Int, ρ::Real)
Create a ``m\\times n`` random masked diagonal coupled square lattice graph,
with number of vertices equal to ``\\lfloor m \\times n\\times \\rho \\rceil``.
"""
function random_diagonal_coupled_graph(m::Int, n::Int, ρ::Real)
@assert ρ >=0 && ρ <= 1
diagonal_coupled_graph(generate_mask(m, n, round(Int,m*n*ρ)))
end
function generate_mask(Nx::Int, Ny::Int, natoms::Int)
mask = zeros(Bool, Nx, Ny)
mask[StatsBase.sample(1:Nx*Ny, natoms; replace=false)] .= true
return mask
end
"""
diagonal_coupled_graph(mask::AbstractMatrix{Bool})
Create a masked diagonal coupled square lattice graph from a specified `mask`.
"""
function diagonal_coupled_graph(mask::AbstractMatrix{Bool})
locs = [(i, j) for i=1:size(mask, 1), j=1:size(mask, 2) if mask[i,j]]
unit_disk_graph(locs, 1.5)
end
"""
unit_disk_graph(locs::AbstractVector, unit::Real)
Create a unit disk graph with locations specified by `locs` and unit distance `unit`.
"""
function unit_disk_graph(locs::AbstractVector, unit::Real)
n = length(locs)
g = SimpleGraph(n)
for i=1:n, j=i+1:n
if sum(abs2, locs[i] .- locs[j]) < unit ^ 2
add_edge!(g, i, j)
end
end
return g
end
"""
line_graph(g::SimpleGraph)
Returns the line graph of `g`.
The line graph is generated by mapping an edge to a vertex and two edges sharing a common vertex will be connected.
"""
function line_graph(graph::SimpleGraph)
edge_list = collect(edges(graph))
linegraph = SimpleGraph(length(edge_list))
for (i, ei) in enumerate(edge_list)
for (j, ej) in enumerate(edge_list)
if ei.src ∈ (ej.src, ej.dst) || ei.dst ∈ (ej.src, ej.dst)
add_edge!(linegraph, i, j)
end
end
end
return linegraph
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 24425 | abstract type AbstractProperty end
struct Single end
_asint(x::Integer) = x
_asint(x::Type{Single}) = 1
"""
SizeMax{K} <: AbstractProperty
SizeMax(k::Int)
The maximum-K set sizes. e.g. the largest size of the [`IndependentSet`](@ref) problem is also know as the independence number.
* The corresponding tensor element type are max-plus tropical number [`Tropical`](@ref) if `K` is `Single` and [`ExtendedTropical`](@ref) if `K` is an integer.
* It is compatible with weighted graph problems.
* BLAS (on CPU) and GPU are supported only if `K` is `Single`,
"""
struct SizeMax{K} <: AbstractProperty end
SizeMax(k::Union{Int,Type{Single}}=Single) = (@assert k == Single || k > 0; SizeMax{k}())
max_k(::SizeMax{K}) where K = K
"""
SizeMin{K} <: AbstractProperty
SizeMin(k::Int)
The minimum-K set sizes. e.g. the smallest size ofthe [`MaximalIS`](@ref) problem is also known as the independent domination number.
* The corresponding tensor element type are inverted max-plus tropical number [`Tropical`](@ref) if `K` is `Single` and inverted [`ExtendedTropical`](@ref) `K` is an integer.
The inverted Tropical number emulates the min-plus tropical number.
* It is compatible with weighted graph problems.
* BLAS (on CPU) and GPU are supported only if `K` is `Single`,
"""
struct SizeMin{K} <: AbstractProperty end
SizeMin(k::Union{Int,Type{Single}}=Single) = (@assert k == Single || k > 0; SizeMin{k}())
max_k(::SizeMin{K}) where K = K
"""
CountingAll <: AbstractProperty
CountingAll()
Counting the total number of sets. e.g. for the [`IndependentSet`](@ref) problem, it counts the independent sets.
* The corresponding tensor element type is `Base.Real`.
* The weights on graph does not have effect.
* BLAS (GPU and CPU) and GPU are supported,
"""
struct CountingAll <: AbstractProperty end
"""
$TYPEDEF
$FIELDS
Compute the partition function for the target problem.
* The corresponding tensor element type is `T`.
"""
struct PartitionFunction{T} <: AbstractProperty
beta::T
end
"""
CountingMax{K} <: AbstractProperty
CountingMax(K=Single)
Counting the number of sets with largest-K size. e.g. for [`IndependentSet`](@ref) problem,
it counts independent sets of size ``\\alpha(G), \\alpha(G)-1, \\ldots, \\alpha(G)-K+1``.
* The corresponding tensor element type is [`CountingTropical`](@ref) if `K` is `Single`, and [`TruncatedPoly`](@ref)`{K}` if `K` is an integer.
* Weighted graph problems is only supported if `K` is `Single`.
* GPU is supported,
"""
struct CountingMax{K} <: AbstractProperty end
CountingMax(k::Union{Int,Type{Single}}=Single) = (@assert k == Single || k > 0; CountingMax{k}())
max_k(::CountingMax{K}) where K = K
"""
CountingMin{K} <: AbstractProperty
CountingMin(K=Single)
Counting the number of sets with smallest-K size.
* The corresponding tensor element type is inverted [`CountingTropical`](@ref) if `K` is `Single`, and [`TruncatedPoly`](@ref)`{K}` if `K` is an integer.
* Weighted graph problems is only supported if `K` is `Single`.
* GPU is supported,
"""
struct CountingMin{K} <: AbstractProperty end
CountingMin(k::Union{Int,Type{Single}}=Single) = (@assert k == Single || k > 0; CountingMin{k}())
min_k(::CountingMin{K}) where K = K
"""
GraphPolynomial{METHOD} <: AbstractProperty
GraphPolynomial(; method=:finitefield, kwargs...)
Compute the graph polynomial, e.g. for [`IndependentSet`](@ref) problem, it is the independence polynomial.
The `METHOD` type parameter can be one of the following symbols
Method Argument
---------------------------
* `:finitefield`, uses finite field algebra to fit the polynomial.
* The corresponding tensor element type is [`Mods.Mod`](@ref),
* It does not have round-off error,
* GPU is supported,
* It accepts keyword arguments `maxorder` (optional, e.g. the MIS size in the [`IndependentSet`](@ref) problem).
* `:polynomial` and `:laurent`, use (Laurent) polynomial numbers to solve the polynomial directly.
* The corresponding tensor element types are [`Polynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomial-2) and [`LaurentPolynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomials.LaurentPolynomial).
* It might have small round-off error depending on the data type for storing the counting.
* It has memory overhead that linear to the graph size.
* `:fft`, use fast fourier transformation to fit the polynomial.
* The corresponding tensor element type is `Base.Complex`.
* It has (controllable) round-off error.
* BLAS and GPU are supported.
* It accepts keyword arguments `maxorder` (optional) and `r`,
if `r > 1`, one has better precision for coefficients of large order, if `r < 1`,
one has better precision for coefficients of small order.
* `:fitting`, fit the polynomial directly.
* The corresponding tensor element type is floating point numbers like `Base.Float64`.
* It has round-off error.
* BLAS and GPU are supported, it is the fastest among all methods.
Graph polynomials are not defined for weighted graph problems.
"""
struct GraphPolynomial{METHOD} <: AbstractProperty
kwargs
end
GraphPolynomial(; method::Symbol = :finitefield, kwargs...) = GraphPolynomial{method}(kwargs)
graph_polynomial_method(::GraphPolynomial{METHOD}) where METHOD = METHOD
"""
SingleConfigMax{K, BOUNDED} <: AbstractProperty
SingleConfigMax(k::Int; bounded=false)
Finding single solution for largest-K sizes, e.g. for [`IndependentSet`](@ref) problem, it is one of the maximum independent sets.
* The corresponding data type is [`CountingTropical{Float64,<:ConfigSampler}`](@ref) if `BOUNDED` is `false`, [`Tropical`](@ref) otherwise.
* Weighted graph problems is supported.
* GPU is supported,
Keyword Arguments
----------------------------
* `bounded`, if it is true, use bounding trick (or boolean gradients) to reduce the working memory to store intermediate configurations.
"""
struct SingleConfigMax{K,BOUNDED} <:AbstractProperty end
SingleConfigMax(k::Union{Int,Type{Single}}=Single; bounded::Bool=false) = (@assert k == Single || k > 0; SingleConfigMax{k, bounded}())
max_k(::SingleConfigMax{K}) where K = K
"""
SingleConfigMin{K, BOUNDED} <: AbstractProperty
SingleConfigMin(k::Int; bounded=false)
Finding single solution with smallest-K size.
* The corresponding data type is inverted [`CountingTropical{Float64,<:ConfigSampler}`](@ref) if `BOUNDED` is `false`, inverted [`Tropical`](@ref) otherwise.
* Weighted graph problems is supported.
* GPU is supported,
Keyword Arguments
----------------------------
* `bounded`, if it is true, use bounding trick (or boolean gradients) to reduce the working memory to store intermediate configurations.
"""
struct SingleConfigMin{K,BOUNDED} <:AbstractProperty end
SingleConfigMin(k::Union{Int,Type{Single}}=Single; bounded::Bool=false) = (@assert k == Single || k > 0; SingleConfigMin{k,bounded}())
min_k(::SingleConfigMin{K}) where K = K
"""
ConfigsAll{TREESTORAGE} <:AbstractProperty
ConfigsAll(; tree_storage=false)
Find all valid configurations, e.g. for [`IndependentSet`](@ref) problem, it is finding all independent sets.
* The corresponding data type is [`ConfigEnumerator`](@ref).
* Weights do not take effect.
Keyword Arguments
----------------------------
* `tree_storage`, if it is true, it uses more memory efficient tree-structure to store the configurations.
"""
struct ConfigsAll{TREESTORAGE} <:AbstractProperty end
ConfigsAll(; tree_storage::Bool=false) = ConfigsAll{tree_storage}()
tree_storage(::ConfigsAll{TREESTORAGE}) where {TREESTORAGE} = TREESTORAGE
"""
ConfigsMax{K, BOUNDED, TREESTORAGE} <:AbstractProperty
ConfigsMax(K=Single; bounded=true, tree_storage=true)
Find configurations with largest-K sizes, e.g. for [`IndependentSet`](@ref) problem,
it is finding all independent sets of sizes ``\\alpha(G), \\alpha(G)-1, \\ldots, \\alpha(G)-K+1``.
* The corresponding data type is [`CountingTropical`](@ref)`{Float64,<:ConfigEnumerator}` if `K` is `Single` and [`TruncatedPoly`](@ref)`{K,<:ConfigEnumerator}` if `K` is an integer.
* Weighted graph problems is only supported if `K` is `Single`.
Keyword Arguments
----------------------------
* `bounded`, if it is true, use bounding trick (or boolean gradients) to reduce the working memory to store intermediate configurations.
* `tree_storage`, if it is true, it uses more memory efficient tree-structure to store the configurations.
"""
struct ConfigsMax{K, BOUNDED, TREESTORAGE} <:AbstractProperty end
ConfigsMax(k::Union{Int,Type{Single}}=Single; bounded::Bool=true, tree_storage::Bool=false) = (@assert k == Single || k > 0; ConfigsMax{k,bounded,tree_storage}())
max_k(::ConfigsMax{K}) where K = K
tree_storage(::ConfigsMax{K,BOUNDED,TREESTORAGE}) where {K,BOUNDED,TREESTORAGE} = TREESTORAGE
"""
ConfigsMin{K, BOUNDED, TREESTORAGE} <:AbstractProperty
ConfigsMin(K=Single; bounded=true, tree_storage=false)
Find configurations with smallest-K sizes.
* The corresponding data type is inverted [`CountingTropical`](@ref)`{Float64,<:ConfigEnumerator}` if `K` is `Single` and inverted [`TruncatedPoly`](@ref)`{K,<:ConfigEnumerator}` if `K` is an integer.
* Weighted graph problems is only supported if `K` is `Single`.
Keyword Arguments
----------------------------
* `bounded`, if it is true, use bounding trick (or boolean gradients) to reduce the working memory to store intermediate configurations.
* `tree_storage`, if it is true, it uses more memory efficient tree-structure to store the configurations.
"""
struct ConfigsMin{K, BOUNDED, TREESTORAGE} <:AbstractProperty end
ConfigsMin(k::Union{Int,Type{Single}}=Single; bounded::Bool=true, tree_storage::Bool=false) = (@assert k == Single || k > 0; ConfigsMin{k,bounded, tree_storage}())
min_k(::ConfigsMin{K}) where K = K
tree_storage(::ConfigsMin{K,BOUNDED,TREESTORAGE}) where {K,BOUNDED,TREESTORAGE} = TREESTORAGE
"""
solve(problem, property; usecuda=false, T=Float64)
Solving a certain property of a graph problem.
Positional Arguments
---------------------------
* `problem` is the graph problem with tensor network information,
* `property` is string specifying the task. Using the maximum independent set problem as an example, it can be one of
* [`PartitionFunction`](@ref)`()` for computing the partition function,
* [`SizeMax`](@ref)`(k=Single)` for finding maximum-``k`` set sizes,
* [`SizeMin`](@ref)`(k=Single)` for finding minimum-``k`` set sizes,
* [`CountingMax`](@ref)`(k=Single)` for counting configurations with maximum-``k`` sizes,
* [`CountingMin`](@ref)`(k=Single)` for counting configurations with minimum-``k`` sizes,
* [`CountingAll`](@ref)`()` for counting all configurations,
* [`PartitionFunction`](@ref)`()` for counting all configurations,
* [`GraphPolynomial`](@ref)`(; method=:finitefield, kwargs...)` for evaluating the graph polynomial,
* [`SingleConfigMax`](@ref)`(k=Single; bounded=false)` for finding one maximum-``k`` configuration for each size,
* [`SingleConfigMin`](@ref)`(k=Single; bounded=false)` for finding one minimum-``k`` configuration for each size,
* [`ConfigsMax`](@ref)`(k=Single; bounded=true, tree_storage=false)` for enumerating configurations with maximum-``k`` sizes,
* [`ConfigsMin`](@ref)`(k=Single; bounded=true, tree_storage=false)` for enumerating configurations with minimum-``k`` sizes,
* [`ConfigsAll`](@ref)`(; tree_storage=false)` for enumerating all configurations,
Keyword arguments
-------------------------------------
* `usecuda` is a switch to use CUDA (if possible), user need to call statement `using CUDA` before turning on this switch.
* `T` is the "base" element type, sometimes can be used to reduce the memory cost.
"""
function solve(gp::GenericTensorNetwork, property::AbstractProperty; T=Float64, usecuda=false)
assert_solvable(gp, property)
if property isa SizeMax{Single}
return contractx(gp, _x(Tropical{T}; invert=false); usecuda=usecuda)
elseif property isa SizeMin{Single}
res = contractx(gp, _x(Tropical{T}; invert=true); usecuda=usecuda)
return asarray(post_invert_exponent.(res), res)
elseif property isa SizeMax
return contractx(gp, _x(ExtendedTropical{max_k(property), Tropical{T}}; invert=false); usecuda=usecuda)
elseif property isa SizeMin
res = contractx(gp, _x(ExtendedTropical{max_k(property), Tropical{T}}; invert=true); usecuda=usecuda)
return asarray(post_invert_exponent.(res), res)
elseif property isa CountingAll
return contractx(gp, one(T); usecuda=usecuda)
elseif property isa PartitionFunction
return contractx(gp, exp(property.beta); usecuda=usecuda)
elseif property isa CountingMax{Single}
return contractx(gp, _x(CountingTropical{T,T}; invert=false); usecuda=usecuda)
elseif property isa CountingMin{Single}
res = contractx(gp, _x(CountingTropical{T,T}; invert=true); usecuda=usecuda)
return asarray(post_invert_exponent.(res), res)
elseif property isa CountingMax
return contractx(gp, TruncatedPoly(ntuple(i->i == max_k(property) ? one(T) : zero(T), max_k(property)), one(T)); usecuda=usecuda)
elseif property isa CountingMin
res = contractx(gp, pre_invert_exponent(TruncatedPoly(ntuple(i->i == min_k(property) ? one(T) : zero(T), min_k(property)), one(T))); usecuda=usecuda)
return asarray(post_invert_exponent.(res), res)
elseif property isa GraphPolynomial
ws = get_weights(gp)
if !(eltype(ws) <: Integer)
@warn "Input weights are not Integer types, try casting to weights of `Int64` type..."
gp = chweights(gp, Int.(ws))
ws = get_weights(gp)
end
n = length(energy_terms(gp))
if ws isa UnitWeight || ws isa ZeroWeight || all(i->all(>=(0), get_weights(gp, i)), 1:n)
return graph_polynomial(gp, Val(graph_polynomial_method(property)); usecuda=usecuda, T=T, property.kwargs...)
elseif all(i->all(<=(0), get_weights(gp, i)), 1:n)
res = graph_polynomial(chweights(gp, -ws), Val(graph_polynomial_method(property)); usecuda=usecuda, T=T, property.kwargs...)
return asarray(invert_polynomial.(res), res)
else
if graph_polynomial_method(property) != :laurent
@warn "Weights are not all positive or all negative, switch to using laurent polynomial."
end
return graph_polynomial(gp, Val(:laurent); usecuda=usecuda, T=T, property.kwargs...)
end
elseif property isa SingleConfigMax{Single,false}
return solutions(gp, CountingTropical{T,T}; all=false, usecuda=usecuda)
elseif property isa (SingleConfigMax{K,false} where K)
return solutions(gp, ExtendedTropical{max_k(property),CountingTropical{T,T}}; all=false, usecuda=usecuda)
elseif property isa SingleConfigMin{Single,false}
return solutions(gp, CountingTropical{T,T}; all=false, usecuda=usecuda, invert=true)
elseif property isa (SingleConfigMin{K,false} where K)
return solutions(gp, ExtendedTropical{min_k(property),CountingTropical{T,T}}; all=false, usecuda=usecuda, invert=true)
elseif property isa ConfigsMax{Single,false}
return solutions(gp, CountingTropical{T,T}; all=true, usecuda=usecuda, tree_storage=tree_storage(property))
elseif property isa ConfigsMin{Single,false}
return solutions(gp, CountingTropical{T,T}; all=true, usecuda=usecuda, invert=true, tree_storage=tree_storage(property))
elseif property isa (ConfigsMax{K, false} where K)
return solutions(gp, TruncatedPoly{max_k(property),T,T}; all=true, usecuda=usecuda, tree_storage=tree_storage(property))
elseif property isa (ConfigsMin{K, false} where K)
return solutions(gp, TruncatedPoly{min_k(property),T,T}; all=true, usecuda=usecuda, invert=true)
elseif property isa ConfigsAll
return solutions(gp, Real; all=true, usecuda=usecuda, tree_storage=tree_storage(property))
elseif property isa SingleConfigMax{Single,true}
return best_solutions(gp; all=false, usecuda=usecuda, T=T)
elseif property isa (SingleConfigMax{K,true} where K)
@warn "bounded `SingleConfigMax` property for `K != Single` is not implemented. Switching to the unbounded version."
return solve(gp, SingleConfigMax{max_k(property),false}(); T, usecuda)
elseif property isa SingleConfigMin{Single,true}
return best_solutions(gp; all=false, usecuda=usecuda, invert=true, T=T)
elseif property isa (SingleConfigMin{K,true} where K)
@warn "bounded `SingleConfigMin` property for `K != Single` is not implemented. Switching to the unbounded version."
return solve(gp, SingleConfigMin{min_k(property),false}(); T, usecuda)
elseif property isa ConfigsMax{Single,true}
return best_solutions(gp; all=true, usecuda=usecuda, tree_storage=tree_storage(property), T=T)
elseif property isa ConfigsMin{Single,true}
return best_solutions(gp; all=true, usecuda=usecuda, invert=true, tree_storage=tree_storage(property), T=T)
elseif property isa (ConfigsMax{K,true} where K)
return bestk_solutions(gp, max_k(property), tree_storage=tree_storage(property), T=T)
elseif property isa (ConfigsMin{K,true} where K)
return bestk_solutions(gp, min_k(property), invert=true, tree_storage=tree_storage(property), T=T)
else
error("unknown property: `$property`.")
end
end
# raise an error if the property for problem can not be computed
assert_solvable(::Any, ::Any) = nothing
function assert_solvable(problem, property::GraphPolynomial)
if has_noninteger_weights(problem)
throw(ArgumentError("Graph property `$(typeof(property))` is not computable due to having non-integer weights."))
end
end
function assert_solvable(problem, property::ConfigsMax)
if max_k(property) != Single && has_noninteger_weights(problem)
throw(ArgumentError("Graph property `$(typeof(property))` is not computable due to having non-integer weights. Maybe you wanted `SingleConfigMax($(max_k(property)))`?"))
end
end
function assert_solvable(problem, property::ConfigsMin)
if min_k(property) != Single && has_noninteger_weights(problem)
throw(ArgumentError("Graph property `$(typeof(property))` is not computable due to having non-integer weights. Maybe you wanted `SingleConfigMin($(min_k(property)))`?"))
end
end
function assert_solvable(problem, property::CountingMax)
if max_k(property) != Single && has_noninteger_weights(problem)
throw(ArgumentError("Graph property `$(typeof(property))` is not computable due to having non-integer weights. Maybe you wanted `SizeMax($(max_k(property)))`?"))
end
end
function assert_solvable(problem, property::CountingMin)
if min_k(property) != Single && has_noninteger_weights(problem)
throw(ArgumentError("Graph property `$(typeof(property))` is not computable due to having non-integer weights. Maybe you wanted `SizeMin($(min_k(property)))`?"))
end
end
function has_noninteger_weights(problem::GenericTensorNetwork)
for i in 1:length(energy_terms(problem))
if any(!isinteger, get_weights(problem, i))
return true
end
end
return false
end
"""
$TYPEDSIGNATURES
Returns the maximum size of the graph problem.
A shorthand of `solve(problem, SizeMax(); usecuda=false)`.
"""
max_size(m::GenericTensorNetwork; usecuda=false)::Int = Int(sum(solve(m, SizeMax(); usecuda=usecuda)).n) # floating point number is faster (BLAS)
"""
$TYPEDSIGNATURES
Returns the maximum size and the counting of the graph problem.
It is a shorthand of `solve(problem, CountingMax(); usecuda=false)`.
"""
max_size_count(m::GenericTensorNetwork; usecuda=false)::Tuple{Int,Int} = (r = sum(solve(m, CountingMax(); usecuda=usecuda)); (Int(r.n), Int(r.c)))
########## memory estimation ###############
"""
$TYPEDSIGNATURES
Memory estimation in number of bytes to compute certain `property` of a `problem`.
`T` is the base type.
"""
function estimate_memory(problem::GenericTensorNetwork, property::AbstractProperty; T=Float64)::Real
_estimate_memory(tensor_element_type(T, length(labels(problem)), nflavor(problem), property), problem)
end
function estimate_memory(problem::GenericTensorNetwork, property::Union{SingleConfigMax{K,BOUNDED},SingleConfigMin{K,BOUNDED}}; T=Float64) where {K, BOUNDED}
tc, sc, rw = contraction_complexity(problem.code, _size_dict(problem))
# caching all tensors is equivalent to counting the total number of writes
if K === Single && BOUNDED
return ceil(Int, exp2(rw - 1)) * sizeof(Tropical{T})
elseif K === Single && !BOUNDED
n, nf = length(labels(problem)), nflavor(problem)
return peak_memory(problem.code, _size_dict(problem)) * (sizeof(tensor_element_type(T, n, nf, property)))
else
# NOTE: the integer `K` case does not respect bounding
n, nf = length(labels(problem)), nflavor(problem)
TT = tensor_element_type(T, n, nf, property)
return peak_memory(problem.code, _size_dict(problem)) * (sizeof(tensor_element_type(T, n, nf, SingleConfigMax{Single,BOUNDED}())) * K + sizeof(TT))
end
end
function estimate_memory(problem::GenericTensorNetwork, ::GraphPolynomial{:polynomial}; T=Float64)
# this is the upper bound
return peak_memory(problem.code, _size_dict(problem)) * (sizeof(T) * length(labels(problem)))
end
function estimate_memory(problem::GenericTensorNetwork, ::GraphPolynomial{:laurent}; T=Float64)
# this is the upper bound
return peak_memory(problem.code, _size_dict(problem)) * (sizeof(T) * length(labels(problem)))
end
function estimate_memory(problem::GenericTensorNetwork, ::Union{SizeMax{K},SizeMin{K}}; T=Float64) where K
return peak_memory(problem.code, _size_dict(problem)) * (sizeof(T) * _asint(K))
end
function _size_dict(problem)
lbs = labels(problem)
nf = nflavor(problem)
return Dict([lb=>nf for lb in lbs])
end
function _estimate_memory(::Type{ET}, problem::GenericTensorNetwork) where ET
if !isbitstype(ET) && !(ET <: Mod)
@warn "Target tensor element type `$ET` is not a bits type, the estimation of memory might be unreliable."
end
return peak_memory(problem.code, _size_dict(problem)) * sizeof(ET)
end
for (PROP, ET) in [
(:(PartitionFunction{T}), :(T)),
(:(SizeMax{Single}), :(Tropical{T})), (:(SizeMin{Single}), :(Tropical{T})),
(:(CountingAll), :T), (:(CountingMax{Single}), :(CountingTropical{T,T})), (:(CountingMin{Single}), :(CountingTropical{T,T})),
(:(GraphPolynomial{:polynomial}), :(Polynomial{T, :x})), (:(GraphPolynomial{:fitting}), :T),
(:(GraphPolynomial{:laurent}), :(LaurentPolynomial{T, :x})), (:(GraphPolynomial{:fft}), :(Complex{T})),
(:(GraphPolynomial{:finitefield}), :(Mod{N,Int32} where N))
]
@eval tensor_element_type(::Type{T}, n::Int, nflavor::Int, ::$PROP) where {T} = $ET
end
for (PROP, ET) in [
(:(SizeMax{K}), :(ExtendedTropical{K,Tropical{T}})), (:(SizeMin{K}), :(ExtendedTropical{K,Tropical{T}})),
(:(CountingMax{K}), :(TruncatedPoly{K,T,T})), (:(CountingMin{K}), :(TruncatedPoly{K,T,T})),
]
@eval tensor_element_type(::Type{T}, n::Int, nflavor::Int, ::$PROP) where {T, K} = $ET
end
function tensor_element_type(::Type{T}, n::Int, nflavor::Int, ::PROP) where {T, K, BOUNDED, PROP<:Union{SingleConfigMax{K,BOUNDED},SingleConfigMin{K,BOUNDED}}}
if K === Single && BOUNDED
return Tropical{T}
elseif K === Single && !BOUNDED
return sampler_type(CountingTropical{T,T}, n, nflavor)
else
# NOTE: the integer `K` case does not respect bounding
return sampler_type(ExtendedTropical{K,CountingTropical{T,T}}, n, nflavor)
end
end
for (PROP, ET) in [
(:(ConfigsMax{Single}), :(CountingTropical{T,T})), (:(ConfigsMin{Single}), :(CountingTropical{T,T})),
(:(ConfigsAll), :(Real))
]
@eval function tensor_element_type(::Type{T}, n::Int, nflavor::Int, ::$PROP) where {T}
set_type($ET, n, nflavor)
end
end
for (PROP, ET) in [
(:(ConfigsMax{K}), :(TruncatedPoly{K,T,T})), (:(ConfigsMin{K}), :(TruncatedPoly{K,T,T})),
]
@eval function tensor_element_type(::Type{T}, n::Int, nflavor::Int, ::$PROP) where {T, K}
set_type($ET, n, nflavor)
end
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1796 | module SimpleMultiprocessing
using Distributed
export multiprocess_run
function do_work(f, jobs, results) # define work function everywhere
while true
job = take!(jobs)
@info "running argument $job on device $(Distributed.myid())"
res = f(job)
put!(results, res)
end
end
"""
multiprocess_run(func, inputs::AbstractVector)
Execute function `func` on `inputs` with multiple processing.
Example
---------------------------
Suppose we have a file `run.jl` with the following contents
```julia
using GenericTensorNetworks.SimpleMultiprocessing
results = multiprocess_run(x->x^2, randn(8))
```
In an terminal, you may run the script with 4 processes by typing
```bash
\$ julia -p4 run.jl
From worker 2: [ Info: running argument -0.17544008350172655 on device 2
From worker 5: [ Info: running argument 0.34578117779452555 on device 5
From worker 3: [ Info: running argument 2.0312551239727705 on device 3
From worker 4: [ Info: running argument -0.7319353419291961 on device 4
From worker 2: [ Info: running argument 0.013132180639054629 on device 2
From worker 3: [ Info: running argument 0.9960101782201602 on device 3
From worker 4: [ Info: running argument -0.5613942832743966 on device 4
From worker 5: [ Info: running argument 0.39460402723831134 on device 5
```
"""
function multiprocess_run(func, inputs::AbstractVector{T}) where T
n = length(inputs)
jobs = RemoteChannel(()->Channel{T}(n));
results = RemoteChannel(()->Channel{Any}(n));
for i in 1:n
put!(jobs, inputs[i])
end
for p in workers() # start tasks on the workers to process requests in parallel
remote_do(do_work, p, func, jobs, results)
end
return Any[take!(results) for i=1:n]
end
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 543 | # Return a vector of unique labels in an Einsum token.
function labels(code::AbstractEinsum)
res = []
for ix in getixsv(code)
for l in ix
if l ∉ res
push!(res, l)
end
end
end
return res
end
# a unified interface to optimize the contraction code
_optimize_code(code, size_dict, optimizer::Nothing, simplifier) = code
_optimize_code(code, size_dict, optimizer, simplifier) = optimize_code(code, size_dict, optimizer, simplifier)
# upload tensors to GPU
function togpu end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 6921 | """
show_einsum(ein::AbstractEinsum;
tensor_locs=nothing,
label_locs=nothing, # dict
spring::Bool=true,
optimal_distance=25.0,
tensor_size=15,
tensor_color="black",
tensor_text_color="white",
annotate_tensors=false,
label_size=7,
label_color="black",
open_label_color="black",
annotate_labels=true,
kwargs...
)
Positional arguments
-----------------------------
* `ein` is an Einsum contraction code (provided by package `OMEinsum`).
Keyword arguments
-----------------------------
* `locs` is a tuple of `tensor_locs` (vector) and `label_locs` (dict).
* `spring` is switch to use spring method to optimize the location.
* `optimal_distance` is a optimal distance parameter for `spring` optimizer.
* `tensor_color` is a string to specify the color of tensor nodes.
* `tensor_size` is a real number to specify the size of tensor nodes.
* `tensor_text_color` is a color strings to specify tensor text color.
* `annotate_tensors` is a boolean switch for annotate different tensors by integers.
* `label_size` is a real number to specify label text node size.
* `label_color` is a color strings to specify label text color.
* `open_label_color` is a color strings to specify open label text color.
* `annotate_labels` is a boolean switch for annotate different labels.
* `format` is the output format, which can be `:svg`, `:png` or `:pdf`.
* `filename` is a string as the output filename.
$(LuxorGraphPlot.CONFIGHELP)
"""
function show_einsum(ein::AbstractEinsum;
label_size=7,
label_color="black",
open_label_color="black",
tensor_size=15,
tensor_color="black",
tensor_text_color="white",
annotate_labels=true,
annotate_tensors=false,
layout = SpringLayout(),
locs = nothing, # dict
filename = nothing,
format=:svg,
padding_left=10.0,
padding_right=10.0,
padding_top=10.0,
padding_bottom=10.0,
config=LuxorGraphPlot.GraphDisplayConfig(; vertex_line_width=0.0),
tensor_texts = nothing,
)
layout = deepcopy(layout)
ixs = getixsv(ein)
iy = getiyv(ein)
labels = uniquelabels(ein)
m = length(labels)
n = length(ixs)
labelmap = Dict(zip(labels, 1:m))
colors = [["transparent" for l in labels]..., fill(tensor_color, n)...]
sizes = [fill(label_size, m)..., fill(tensor_size, n)...]
if tensor_texts === nothing
tensor_texts = [annotate_tensors ? "$i" : "" for i=1:n]
end
texts = [[annotate_labels ? "$(labels[i])" : "" for i=1:m]..., tensor_texts...]
vertex_text_colors = [[l ∈ iy ? open_label_color : label_color for l in labels]..., [tensor_text_color for ix in ixs]...]
graph = SimpleGraph(m+n)
for (j, ix) in enumerate(ixs)
for l in ix
add_edge!(graph, j+m, labelmap[l])
end
end
if locs === nothing
locs = getfield.(LuxorGraphPlot.render_locs(graph, layout), :data)
else
tensor_locs, label_locs = locs
@assert tensor_locs isa AbstractVector && label_locs isa AbstractDict "locs should be a tuple of `tensor_locs` (vector) and `label_locs` (dict)"
@assert length(tensor_locs) == n "the length of tensor_locs should be $n"
@assert length(label_locs) == m "the length of label_locs should be $m"
locs = [[label_locs[l] for l in labels]..., tensor_locs...]
end
show_graph(GraphViz(; locs, edges=[(e.src, e.dst) for e in edges(graph)], texts, vertex_colors=colors,
vertex_text_colors,
vertex_sizes=sizes);
filename, format,
padding_left, padding_right, padding_top, padding_bottom, config
)
end
"""
show_configs(gp::GraphProblem, locs, configs::AbstractMatrix; kwargs...)
show_configs(graph::SimpleGraph, locs, configs::AbstractMatrix; nflavor=2, kwargs...)
Show a gallery of configurations on a graph.
"""
function show_configs(gp::GraphProblem, locs, configs::AbstractMatrix; kwargs...)
show_configs(gp.graph, locs, configs; nflavor=nflavor(gp), kwargs...)
end
function show_configs(graph::SimpleGraph, locs, configs::AbstractMatrix;
nflavor::Int=2,
kwargs...)
cmap = range(colorant"white", stop=colorant"red", length=nflavor)
graphs = map(configs) do cfg
@assert all(0 .<= cfg .<= nflavor-1)
GraphViz(graph, locs; vertex_colors=cmap[cfg .+ 1])
end
show_gallery(graphs; kwargs...)
end
"""
show_landscape(is_neighbor, configurations::TruncatedPoly;
layer_distance=200,
config=GraphDisplayConfig(; edge_color="gray", vertex_stroke_color="transparent", vertex_size=5),
layout_method=:spring,
optimal_distance=30.0,
colors=fill("green", K),
kwargs...)
Show the energy landscape of configurations.
### Arguments
- `is_neighbor`: a function to determine if two configurations are neighbors.
- `configurations`: a TruncatedPoly object, which is the default output of the [`solve`](@ref) function with [`ConfigsMax`](@ref) property as the argument.
### Keyword arguments
- `layer_distance`: the distance between layers.
- `config`: a `LuxorGraphPlot.GraphDisplayConfig` object.
- `layout_method`: the layout method, either `:spring`, `:stress` or `:spectral`
- `optimal_distance`: the optimal distance for the layout.
- `colors`: a vector of colors for each layer.
- `kwargs...`: other keyword arguments passed to `show_graph`.
"""
function show_landscape(is_neighbor, configurations::TruncatedPoly{K};
layer_distance=200,
config=GraphDisplayConfig(; edge_color="gray", vertex_stroke_color="transparent", vertex_size=5),
layout_method = :spring,
optimal_distance = 30.0,
colors=fill("green", K),
kwargs...) where K
@assert length(colors) == K "colors should have length $K"
nv = 0
kv = read_size_config(configurations)
zlocs = Float64[]
vertex_colors = String[]
for (c, (k, v)) in zip(colors, kv)
nv += length(v)
append!(zlocs, fill(k*layer_distance, length(v)))
append!(vertex_colors, fill(c, length(v)))
end
graph = SimpleGraph(nv)
configs = vcat(getindex.(kv, 2)...)
for (i, c) in enumerate(configs)
for (j, d) in enumerate(configs)
if is_neighbor(c, d)
add_edge!(graph, i, j)
end
end
end
if layout_method == :spring
layout=LayeredSpringLayout(; zlocs, optimal_distance)
elseif layout_method == :stress
layout=LayeredStressLayout(; zlocs, optimal_distance)
elseif layout_method == :spectral
layout=LuxorGraphPlot.Layered(SpectralLayout(), zlocs, 0.2)
else
error("layout_method should be :spring, :stress or :spectral")
end
show_graph(graph, layout; config, vertex_colors, kwargs...)
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1604 | import Base: mod, real, imag, reim, conj, promote_rule
export GaussMod, AbstractMod
# mod support for Gaussian integers until officially adopted into Base
mod(z::Complex{<:Integer}, n::Integer) = Complex(mod(real(z), n), mod(imag(z), n))
"""
`GaussMod{N,T}` is an alias of `Mod{N,Complex{T}}`.
It is for computing Gaussian Modulus.
"""
const GaussMod{N,T} = Mod{N,Complex{T}}
GaussMod{N}(x::T) where {N,T<:Integer} = Mod{N,Complex{T}}(x)
GaussMod{N}(x::T) where {N,T<:Complex} = Mod{N,T}(x)
Mod{N}(x::Complex{Rational{T}}) where {N,T} = Mod{N}(real(x)) + Mod{N}(imag(x)) * im
Mod{N}(re::Integer, im::Integer) where {N} = Mod{N}(Complex(re, im))
reim(x::AbstractMod) = (real(x), imag(x))
real(x::Mod{N}) where {N} = Mod{N}(real(x.val))
imag(x::Mod{N}) where {N} = Mod{N}(imag(x.val))
conj(x::Mod{N}) where {N} = Mod{N}(conj(x.val))
# ARITHMETIC
function (+)(x::GaussMod{N,T}, y::GaussMod{N,T}) where {N,T}
xx = widen(x.val)
yy = widen(y.val)
zz = mod(xx + yy, N)
return GaussMod{N,T}(zz)
end
(-)(x::GaussMod{N}) where {N} = Mod{N}(-x.val)
function (*)(x::GaussMod{N,T}, y::GaussMod{N,T}) where {N,T}
xx = widen(x.val)
yy = widen(y.val)
zz = mod(xx * yy, N)
return GaussMod{N,T}(zz)
end
function inv(x::GaussMod{N}) where {N}
try
a, b = reim(x)
bot = inv(a * a + b * b)
aa = a * bot
bb = -b * bot
return aa + bb * im
catch
error("$x is not invertible")
end
end
is_invertible(x::GaussMod) = is_invertible(real(x * x'))
rand(::Type{GaussMod{N}}, args::Integer...) where {N} = rand(GaussMod{N,Int}, args...)
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 5651 | module Mods
import Base: (==), (+), (-), (*), (inv), (/), (//), (^), hash, show
import Base: rand, conj, iszero, rtoldefault, isapprox
export Mod, modulus, value, AbstractMod
export is_invertible
export CRT
abstract type AbstractMod <: Number end
"""
`Mod{m}(v)` creates a modular number in mod `m` with value `mod(v,m)`.
"""
struct Mod{N,T} <: AbstractMod
val::T
end
# safe constructors (slower)
function Mod{N}(x::T) where {T<:Integer,N}
@assert N isa Integer && N > 1 "modulus must be an integer and at least 2"
S = typeof(N)
v = mod(x, N)
Mod{N,S}(v)
end
function Mod{N}(x::T) where {T<:Complex{<:Integer},N}
@assert N isa Integer && N > 1 "modulus must be an integer and at least 2"
S = Complex{typeof(N)}
v = mod(x, N)
Mod{N,S}(v)
end
# type casting
Mod{N,T}(x::Mod{N,T2}) where {T,N,T2} = Mod{N,T}(T(x.val))
Mod{N,T}(x::Mod{N,T}) where {T,N} = x
show(io::IO, z::Mod{N}) where {N} = print(io, "Mod{$N}($(value(z)))")
show(io::IO, ::MIME"text/plain", z::Mod{N}) where {N} = show(io, z)
"""
`modulus(a::Mod)` returns the modulus of this `Mod` number.
```
julia> a = Mod{13}(11);
julia> modulus(a)
13
```
"""
modulus(a::Mod{N}) where {N} = N
"""
`value(a::Mod)` returns the value of this `Mod` number.
```
julia> a = Mod{13}(11);
julia> value(a)
11
```
"""
value(a::Mod{N}) where {N} = a.val
Base.abs(a::Mod{N,<:Real} where {N}) = abs(value(a))
function hash(x::Mod, h::UInt64 = UInt64(0))
v = value(x)
m = modulus(x)
return hash(v, hash(m, h))
end
# Test for equality
iszero(x::Mod{N}) where {N} = iszero(x.val)
==(x::Mod, y::Mod) = modulus(x) == modulus(y) && value(y) == value(y)
# ==(x::Mod{N}, y::Mod{N}) where {N} = iszero(value(x - y))
# Apporximate equality
rtoldefault(::Type{Mod{N,T}}) where {N,T} = rtoldefault(T)
isapprox(x::Mod, y::Mod; kwargs...) = false
isapprox(x::Mod{N}, y::Mod{N}; kwargs...) where {N} =
isapprox(value(x), value(y); kwargs...) || isapprox(value(y), value(x); kwargs...)
# Easy arithmetic
@inline function +(x::Mod{N,T}, y::Mod{N,T}) where {N,T}
s, flag = Base.add_with_overflow(x.val, y.val)
if !flag
return Mod{N,T}(s)
end
t = widen(x.val) + widen(y.val) # add with added precision
return Mod{N,T}(mod(t, N))
end
function -(x::Mod{M,T}) where {M,T<:Signed}
if (x.val isa BigInt || x.val == typemin(T))
return Mod{M,T}(-mod(x.val, M))
else
return Mod{M,T}(-x.val)
end
end
function -(x::Mod{M,T}) where {M,T<:Unsigned}
return Mod{M,T}(M - value(x))
end
-(x::Mod, y::Mod) = x + (-y)
@inline function *(x::Mod{N,T}, y::Mod{N,T}) where {N,T}
p, flag = Base.mul_with_overflow(x.val, y.val)
if !flag
return Mod{N,T}(p)
else
q = widemul(x.val, y.val) # multipy with added precision
return Mod{N,T}(mod(q, N)) # return with proper type
end
end
# Division stuff
"""
`is_invertible(x::Mod)` determines if `x` is invertible.
"""
function is_invertible(x::Mod{M})::Bool where {M}
return gcd(x.val, M) == 1
end
"""
`inv(x::Mod)` gives the multiplicative inverse of `x`.
"""
@inline function inv(x::Mod{M,T}) where {M,T}
Mod{M,T}(_invmod(x.val, M))
end
_invmod(x::Unsigned, m::Unsigned) = invmod(x, m)
# faster version of `Base.invmod`, only works for for signed types
@inline function _invmod(x::Signed, m::Signed)
(g, v, _) = gcdx(x, m)
if g != 1
error("$x (mod $m) is not invertible")
end
return v
end
function /(x::Mod{N,T}, y::Mod{N,T}) where {N,T}
return x * inv(y)
end
(//)(x::Mod, y::Mod) = x / y
(//)(x::Number, y::Mod{N}) where {N} = x / y
(//)(x::Mod{N}, y::Number) where {N} = x / y
Base.promote_rule(::Type{Mod{M,T1}}, ::Type{Mod{N,T2}}) where {M,N,T1,T2<:Number} =
error("can not promote types `Mod{$M,$T1}`` and `Mod{$N,$T2}`")
Base.promote_rule(::Type{Mod{M,T1}}, ::Type{Mod{M,T2}}) where {M,T1,T2<:Number} =
Mod{M,promote_type(T1, T2)}
Base.promote_rule(::Type{Mod{M,T1}}, ::Type{T2}) where {M,T1,T2<:Number} =
Mod{M,promote_type(T1, T2)}
Base.promote_rule(::Type{Mod{M,T1}}, ::Type{Rational{T2}}) where {M,T1,T2} =
Mod{M,promote_type(T1, T2)}
# Operations with rational numbers
Mod{N}(k::Rational) where {N} = Mod{N}(numerator(k)) / Mod{N}(denominator(k))
Mod{N,T}(k::Rational{T2}) where {N,T,T2} = Mod{N,T}(numerator(k)) / Mod{N,T}(denominator(k))
# Random
rand(::Type{Mod{N}}, args::Integer...) where {N} = rand(Mod{N,Int}, args...)
rand(::Type{Mod{N,T}}) where {N,T} = Mod{N}(rand(T))
rand(::Type{Mod{N,T}}, dims::Integer...) where {N,T} = Mod{N}.(rand(T, dims...))
# Chinese remainder theorem functions
"""
`CRT([T=BigInt, ]m1, m2,...)`
Chinese Remainder Theorem.
```
julia> CRT(Int, Mod{11}(4), Mod{14}(814))
92
julia> 92%11
4
julia> 92%14
8
julia> CRT(Mod{9223372036854775783}(9223372036854775782), Mod{9223372036854775643}(9223372036854775642))
85070591730234614113402964855534653468
```
!!! note
`CRT` uses `BigInt` by default to prevent potential integer overflow.
If you are confident that numbers do not overflow in your application,
please specify an optional type parameter as the first argument.
"""
function CRT(::Type{T}, remainders, primes) where {T}
length(remainders) == length(primes) || error("size mismatch")
isempty(remainders) && return zero(T)
primes = convert.(T, primes)
M = prod(primes)
Ms = M .÷ primes
ti = _invmod.(Ms, primes)
mod(sum(convert.(T, remainders) .* ti .* Ms), M)
end
function CRT(::Type{T}, rs::Mod...) where {T}
CRT(T, value.(rs), modulus.(rs))
end
CRT(rs::Mod...) = CRT(BigInt, rs...)
include("GaussMods.jl")
include("iterate.jl")
end # end of module Mods
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1992 | real(z::GaussMod{N}) where {N} = Mod{N}(real(value(z)))
imag(z::GaussMod{N}) where {N} = Mod{N}(imag(value(z)))
reim(z::GaussMod) = (real(z), imag(z))
conj(z::GaussMod{N}) where {N} = GaussMod{N}(real(z).val, -imag(z).val)
ACZQ = Union{AbstractMod,CZQ}
function (+)(x::GaussMod{N}, y::GaussMod{N}) where {N}
z = widen(value(x)) + widen(value(y))
GaussMod{N}(z)
end
(+)(x::GaussMod{N}, y::T) where {N,T<:ACZQ} = x + GaussMod{N}(y)
(+)(x::T, y::GaussMod{N}) where {N,T<:ACZQ} = y + GaussMod{N}(x)
(+)(x::Mod, y::T) where {T<:Complex} = GaussMod(x) + y
(+)(x::T, y::Mod) where {T<:Complex} = x + GaussMod(y)
(-)(x::GaussMod{N}) where {N} = GaussMod{N}(-x.val)
(-)(x::GaussMod{N}, y::GaussMod{N}) where {N} = x + (-y)
(-)(x::GaussMod{N}, y::T) where {N,T<:Union{CZQ,Mod}} = x + (-y)
(-)(x::Mod, y::Union{Complex,GaussMod}) = x + (-y)
(-)(x::Union{Complex,GaussMod}, y::Mod) = x + (-y)
function *(x::GaussMod{N}, y::GaussMod{N}) where {N}
z = widemul(x.val, y.val) # multipy with added precision
return GaussMod{N}(z) # return with proper type
end
(*)(x::GaussMod{N}, y::T) where {N,T<:ACZQ} = x * GaussMod{N}(y)
(*)(x::T, y::GaussMod{N}) where {N,T<:ACZQ} = y * x
# (*)(x::Mod{N}, y::Union{GaussMod,Complex}) where N = GaussMod{N}(x) * y
# (*)(x::Union{GaussMod,Complex}, y::Mod) = y * x
is_invertible(x::GaussMod) = is_invertible(real(x * x'))
function inv(x::GaussMod{N}) where {N}
if !is_invertible(x)
error("$x is not invertible")
end
a = value(real(x * x'))
return (1 // a) * conj(x)
end
function (/)(x::GaussMod{N}, y::GaussMod{N}) where {N}
return x * inv(y)
end
(/)(x::GaussMod{N}, y::T) where {N,T<:ACZQ} = x / GaussMod{N}(y)
(/)(x::T, y::GaussMod{N}) where {N,T<:ACZQ} = GaussMod{N}(x) / y
(//)(x::GaussMod, y::GaussMod) = x/y
(//)(x::GaussMod, y::ACZQ) = x/y
(//)(x::ACZQ, y::GaussMod) = x/y
function rand(::Type{GaussMod{N}}, dims::Integer...) where {N}
return GaussMod{N}.(rand(Complex{Int}, dims...))
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 722 | function Base.iterate(::Type{Mod{m}}) where {m}
return Mod{m}(0), 0
end
function Base.iterate(::Type{Mod{m}}, s) where {m}
if s == m - 1
return nothing
end
s += 1
return Mod{m}(s), s
end
Base.IteratorSize(::Type{Mod{m}}) where {m} = Base.HasLength()
Base.length(::Type{Mod{m}}) where {m} = m
function Base.iterate(::Type{GaussMod{m}}) where {m}
return GaussMod{m}(0), 0
end
function Base.iterate(::Type{GaussMod{m}}, s) where {m}
if s == m * m - 1
return nothing
end
s += 1
a, b = divrem(s, m)
return GaussMod{m}(a + b * im), s
end
Base.IteratorSize(::Type{GaussMod{m}}) where {m} = Base.HasLength()
Base.length(::Type{GaussMod{m}}) where {m} = m * m
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1730 | @inline function (+)(x::Mod{N}, y::Mod{N}) where {N}
t = widen(x.val) + widen(y.val) # add with added precision
return Mod{N}(mod(t, N))
end
(+)(x::Mod{N}, y::T) where {N,T<:QZ} = x + Mod{N}(y)
(+)(y::T, x::Mod{N}) where {N,T<:QZ} = x + y
@inline function (-)(x::Mod{M}) where {M}
return Mod{M}(-x.val)
end
@inline (-)(x::Mod, y::Mod) = x + (-y)
(-)(x::Mod, y::T) where {T<:QZ} = x + (-y)
(-)(x::T, y::Mod) where {T<:QZ} = x + (-y)
@inline function *(x::Mod{N}, y::Mod{N}) where {N}
q = widemul(x.val, y.val) # multipy with added precision
return Mod{N}(q) # return with proper type
end
(*)(x::Mod{N}, y::T) where {N,T<:QZ} = x * Mod{N}(y)
(*)(x::T, y::Mod{N}) where {N,T<:QZ} = y * x
# Division stuff
"""
`is_invertible(x::Mod)` determines if `x` is invertible.
"""
@inline function is_invertible(x::Mod{M})::Bool where {M}
return gcd(x.val, M) == 1
end
"""
`inv(x::Mod)` gives the multiplicative inverse of `x`.
"""
@inline function inv(x::Mod{M}) where {M}
Mod{M}(_invmod(x.val, M))
end
_invmod(x::Unsigned, m::Unsigned) = invmod(x, m)
# faster version of `Base.invmod`, only works for for signed types
@inline function _invmod(x::Signed, m::Signed)
(g, v, _) = gcdx(x, m)
if g != 1
error("$x (mod $m) is not invertible")
end
return v
end
function (/)(x::Mod{N}, y::Mod{N}) where {N}
return x * inv(y)
end
(/)(x::Mod{N}, y::T) where {N,T<:QZ} = x / Mod{N}(y)
(/)(x::T, y::Mod{N}) where {N,T<:QZ} = Mod{N}(x) / y
(//)(x::Mod{N}, y::Mod{N}) where {N} = x / y
(//)(x::T, y::Mod{N}) where {N,T<:QZ} = x / y
(//)(x::Mod{N}, y::T) where {N,T<:QZ} = x / y
import Base: rand
rand(::Type{Mod{N}}, dims::Integer...) where {N} = Mod{N}.(rand(Int, dims...))
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 5506 | using Test
using GenericTensorNetworks.Mods
@testset "Constructors" begin
@test one(Mod{17}) == Mod{17}(1)
@test oneunit(Mod{17}) == Mod{17}(1)
@test zero(Mod{17}) == 0
@test iszero(zero(Mod{17}))
@test Mod{17}(1) == Mod{17}(1, 0)
@test Mod{17}(1, 2) == 1 + 2im
a = Mod{17}(3)
@test typeof(a) == Mod{17,Int}
a = Mod{17}(3, 2)
@test typeof(a) == GaussMod{17,Int}
a = zero(Mod{17})
@test typeof(a) == Mod{17,Int}
a = Mod{17}(1 // 2 + (3 // 4)im)
@test typeof(a) == GaussMod{17,Int}
end
@testset "Mod arithmetic" begin
p = 23
a = Mod{p}(2)
b = Mod{p}(25)
@test a == b
@test a == 2
@test a == -21
b = Mod{p}(20)
@test a + b == 22
@test a - b == -18
@test a + a == 2a
@test 0 - a == -a
@test a * b == Mod{p}(17)
@test (a / b) * b == a
@test (b // a) * (2 // 1) == b
@test a * (2 // 3) == (2a) * inv(Mod{p}(3))
@test is_invertible(a)
@test !is_invertible(Mod{10}(4))
@test a^(p - 1) == 1
@test a^(-1) == inv(a)
@test Mod{p}(3 // 7) == 3 // 7
@test isequal(3 // 7, Mod{p}(3 // 7))
@test -Mod{13,Int}(typemin(Int)) == -Mod{13}(mod(typemin(Int), 13))
end
@testset "Mod arithmetic with UInt" begin
p = UInt(23)
a = Mod{p,UInt}(2)
b = Mod{p,UInt}(25)
@test a == b
@test a == 2
@test a == 25
b = Mod{p,UInt}(20)
@test a + b == 22
@test a - b == 28
@test a + a == 2a
@test 0 - a == -a
@test a * b == Mod{p,UInt}(17)
@test (a / b) * b == a
@test (b // a) * (2 // 1) == b
@test a * (2 // 3) == (2a) * inv(Mod{p,UInt}(3))
@test is_invertible(a)
@test !is_invertible(Mod{10}(4))
@test a^(p - 1) == 1
@test a^(-1) == inv(a)
end
@testset "GaussMod arithmetic" begin
@test one(GaussMod{6}) == Mod{6}(1 + 0im)
@test zero(GaussMod{6}) == Mod{6}(0 + 0im)
@test GaussMod{6}(2 + 3im) == Mod{6}(2 + 3im)
@test GaussMod{6,Int}(2 + 3im) == Mod{6}(2 + 3im)
@test rand(GaussMod{6}) isa GaussMod
@test eltype(rand(GaussMod{6}, 4, 4)) <: GaussMod
p = 23
a = GaussMod{p}(3 - im)
b = Mod{p}(5 + 5im)
@test a + b == 8 + 4im
@test a + Mod{p}(11) == Mod{p}(14, 22)
@test -a == 20 + im
@test a - b == Mod{p}(3 - im - 5 - 5im)
@test a * b == Mod{p}((3 - im) * (5 + 5im))
@test a / b == Mod{p}((3 - im) // (5 + 5im))
@test a^(p * p - 1) == 1
@test is_invertible(a)
@test a * inv(a) == 1
@test a / (1 + im) == a / Mod{p}(1 + im)
@test imag(a * a') == 0
end
@testset "Large Modulus" begin
p = 9223372036854775783 # This is a large prime
x = Mod{p}(-2)
@test x * x == 4
@test x + x == -4
@test x / x == 1
@test x / 3 == x / Mod{p}(3)
@test (x / 3) * (3 // x) == 1
@test x // x == value(x) / x
@test x^4 == 16
@test x^(p - 1) == 1 # Fermat Little Theorem test
@test 2x == x + x
@test x - x == 0
y = inv(x)
@test x * y == 1
@test x + p == x
@test x * p == 0
@test p - x == x - 2x
p = 9223372036854775783 # This is a large prime
x = Mod{p}(-2 + 0im)
@test x * x == 4
@test x + x == -4
@test x / x == 1
@test x / 3 == x / Mod{p}(3)
@test (x / 3) * (3 // x) == 1
@test x // x == value(x) / x
@test x^4 == 16
@test x^(p - 1) == 1 # Fermat Little Theorem test
@test 2x == x + x
@test x - x == 0
y = inv(x)
@test x * y == 1
@test x + p == x
@test x * p == 0
@test p - x == x - 2x
@test 0 <= value(rand(Mod{p})) < p
end
@testset "CRT" begin
p = 23
q = 91
a = Mod{p}(17)
b = Mod{q}(32)
@test CRT(Int32, [], []) === Int32(0)
x = CRT(a, b)
@test typeof(x) <: BigInt
@test a == mod(x, p)
@test b == mod(x, q)
c = Mod{101}(86)
x = CRT(Int, a, b, c)
@test typeof(x) <: Int
@test a == mod(x, p)
@test b == mod(x, q)
@test c == mod(x, 101)
@test CRT(
BigInt,
Mod{9223372036854775783}(9223372036854775782),
Mod{9223372036854775643}(9223372036854775642),
) == 85070591730234614113402964855534653468
end
@testset "Matrices" begin
M = zeros(Mod{11}, 3, 3)
@test sum(M) == 0
M = ones(Mod{11}, 5, 5)
@test sum(M) == 3
M = rand(Mod{11}, 5, 6)
@test size(M) == (5, 6)
A = rand(Mod{17}, 5, 5)
X = values.(A)
@test sum(X) == sum(Mod{17}.(A))
end
@testset "Hashing/Iterating" begin
x = Mod{17}(11)
y = x + 0im
@test x == y
@test hash(x) == hash(y)
@test typeof(x) !== typeof(y)
A = Set([x, y])
@test length(A) == 1
v = [Mod{10}(t) for t = 1:15]
w = [Mod{10}(t + 0im) for t = 1:15]
S = Set(v)
T = Set(w)
@test length(S) == 10
@test S == T
@test union(S, T) == intersect(S, T)
end
@testset "Iteration" begin
@test sum(k for k in Mod{7}) == zero(Mod{7})
@test collect(Mod{7}) == Mod{7}.(0:6)
@test prod(k for k in Mod{7} if k != 0) == -1 # Wilson's theorem
@test sum(GaussMod{7}) == 0
@test length(GaussMod{5}) == 25
end
@testset "Linear system solution" begin
A = Mod{13}.([1 2; 3 -4])
b = Mod{13}.([3, 4])
x = A \ b
@test A * x == b
@test inv(A) * b == x
end
@testset "isapprox" begin
@test Mod{7}(3) ≈ Mod{7}(3)
@test Mod{7}(3) ≈ Mod{7}(10)
@test Mod{7}(3) ≈ Mod{7}(10) atol=1
@test Mod{7}(3) ≈ Mod{7}(11) atol=1
@test !isapprox(Mod{7}(3), Mod{7}(11), atol=0)
@test !(Mod{7}(3) ≈ Mod{7}(11))
@test Mod{7}(3) ≈ Mod{7}(11) atol=2
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1970 | """
$(TYPEDEF)
Coloring{K}(graph; weights=UnitWeight())
The [Vertex Coloring](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/Coloring/) problem.
Positional arguments
-------------------------------
* `graph` is the problem graph.
* `weights` are associated with the edges of the `graph`, default to `UnitWeight()`.
"""
struct Coloring{K, WT<:Union{UnitWeight, Vector}} <: GraphProblem
graph::SimpleGraph{Int}
weights::WT
function Coloring{K}(graph::SimpleGraph, weights::Union{UnitWeight, Vector}=UnitWeight()) where {K}
@assert weights isa UnitWeight || length(weights) == ne(graph)
new{K, typeof(weights)}(graph, weights)
end
end
flavors(::Type{<:Coloring{K}}) where K = collect(0:K-1)
energy_terms(gp::Coloring) = [[minmax(e.src,e.dst)...] for e in Graphs.edges(gp.graph)]
energy_tensors(x::T, c::Coloring{K}) where {K, T} = [_pow.(coloringb(x, K), get_weights(c, i)) for i=1:ne(c.graph)]
extra_terms(gp::Coloring) = [[i] for i in 1:nv(gp.graph)]
extra_tensors(::Type{T}, c::Coloring{K}) where {K,T} = [coloringv(T, K) for i=1:nv(c.graph)]
labels(gp::Coloring) = [1:nv(gp.graph)...]
# weights interface
get_weights(c::Coloring) = c.weights
get_weights(c::Coloring{K}, i::Int) where K = fill(c.weights[i], K)
chweights(c::Coloring{K}, weights) where K = Coloring{K}(c.graph, weights)
# coloring bond tensor
function coloringb(x::T, k::Int) where T
x = fill(x, k, k)
for i=1:k
x[i,i] = one(T)
end
return x
end
# coloring vertex tensor
coloringv(::Type{T}, k::Int) where T = fill(one(T), k)
# utilities
"""
is_vertex_coloring(graph::SimpleGraph, config)
Returns true if the coloring specified by config is a valid one, i.e. does not violate the contraints of vertices of an edges having different colors.
"""
function is_vertex_coloring(graph::SimpleGraph, config)
for e in edges(graph)
config[e.src] == config[e.dst] && return false
end
return true
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1825 | """
$TYPEDEF
DominatingSet(graph; weights=UnitWeight())
The [dominating set](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/DominatingSet/) problem.
Positional arguments
-------------------------------
* `graph` is the problem graph.
* `weights` are associated with the vertices of the `graph`, default to `UnitWeight()`.
"""
struct DominatingSet{WT<:Union{UnitWeight, Vector}} <: GraphProblem
graph::SimpleGraph{Int}
weights::WT
function DominatingSet(g::SimpleGraph, weights::Union{UnitWeight, Vector}=UnitWeight())
@assert weights isa UnitWeight || length(weights) == nv(g)
new{typeof(weights)}(g, weights)
end
end
flavors(::Type{<:DominatingSet}) = [0, 1]
energy_terms(gp::DominatingSet) = [[Graphs.neighbors(gp.graph, v)..., v] for v in Graphs.vertices(gp.graph)]
energy_tensors(x::T, c::DominatingSet) where T = [dominating_set_tensor(_pow.(Ref(x), get_weights(c, i))..., degree(c.graph, i)+1) for i=1:nv(c.graph)]
extra_terms(::DominatingSet) = Vector{Int}[]
extra_tensors(::Type{T}, ::DominatingSet) where T = Array{T}[]
labels(gp::DominatingSet) = [1:nv(gp.graph)...]
# weights interface
get_weights(c::DominatingSet) = c.weights
get_weights(gp::DominatingSet, i::Int) = [0, gp.weights[i]]
chweights(c::DominatingSet, weights) = DominatingSet(c.graph, weights)
function dominating_set_tensor(a::T, b::T, d::Int) where T
t = zeros(T, fill(2, d)...)
for i = 2:1<<(d-1)
t[i] = a
end
t[1<<(d-1)+1:end] .= Ref(b)
return t
end
"""
is_dominating_set(g::SimpleGraph, config)
Return true if `config` (a vector of boolean numbers as the mask of vertices) is a dominating set of graph `g`.
"""
is_dominating_set(g::SimpleGraph, config) = all(w->config[w] == 1 || any(v->!iszero(config[v]), neighbors(g, w)), Graphs.vertices(g)) | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3637 | """
$TYPEDEF
The [independent set problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/IndependentSet/) in graph theory.
Positional arguments
-------------------------------
* `graph` is the problem graph.
* `weights` are associated with the vertices of the `graph`, default to `UnitWeight()`.
Examples
-------------------------------
```jldoctest; setup=:(using Random; Random.seed!(2))
julia> using GenericTensorNetworks, Graphs
julia> problem = IndependentSet(smallgraph(:petersen));
julia> net = GenericTensorNetwork(problem);
julia> solve(net, ConfigsMax())
0-dimensional Array{CountingTropical{Float64, ConfigEnumerator{10, 1, 1}}, 0}:
(4.0, {1010000011, 1001001100, 0100100110, 0101010001, 0010111000})ₜ
```
"""
struct IndependentSet{WT} <: GraphProblem
graph::SimpleGraph{Int}
weights::WT
function IndependentSet(graph::SimpleGraph{Int}, weights::WT=UnitWeight()) where WT
@assert weights isa UnitWeight || length(weights) == nv(graph) "got unexpected weights for $(nv(graph))-vertex graph: $weights"
new{WT}(graph, weights)
end
end
flavors(::Type{<:IndependentSet}) = [0, 1]
energy_terms(gp::IndependentSet) = [[i] for i in 1:nv(gp.graph)]
energy_tensors(x::T, c::IndependentSet) where T = [misv(_pow.(Ref(x), get_weights(c, i))) for i=1:nv(c.graph)]
extra_terms(gp::IndependentSet) = [[minmax(e.src,e.dst)...] for e in Graphs.edges(gp.graph)]
extra_tensors(::Type{T}, gp::IndependentSet) where T = [misb(T) for i=1:ne(gp.graph)]
labels(gp::IndependentSet) = [1:nv(gp.graph)...]
# weights interface
get_weights(c::IndependentSet) = c.weights
get_weights(gp::IndependentSet, i::Int) = [0, gp.weights[i]]
chweights(c::IndependentSet, weights) = IndependentSet(c.graph, weights)
function misb(::Type{T}, n::Integer=2) where T
res = zeros(T, fill(2, n)...)
res[1] = one(T)
for i=1:n
res[1+1<<(i-1)] = one(T)
end
return res
end
misv(vals) = vals
"""
mis_compactify!(tropicaltensor; potential=nothing)
Compactify tropical tensor for maximum independent set problem. It will eliminate
some entries by setting them to zero, by the criteria that removing these entry
does not change the MIS size of its parent graph (reference to be added).
### Arguments
- `tropicaltensor::AbstractArray{T}`: the tropical tensor
### Keyword arguments
- `potential=nothing`: the maximum possible MIS contribution from each open vertex
"""
function mis_compactify!(a::AbstractArray{T, N}; potential=nothing) where {T <: TropicalTypes, N}
@assert potential === nothing || length(potential) == N "got unexpected potential length: $(length(potential)), expected $N"
for (ind_a, val_a) in enumerate(a)
for (ind_b, val_b) in enumerate(a)
bs_a = ind_a - 1
bs_b = ind_b - 1
if worse_than(bs_a, bs_b, val_a.n, val_b.n, potential)
@inbounds a[ind_a] = zero(T)
end
end
end
return a
end
function worse_than(bs_a::Integer, bs_b::Integer, val_a::T, val_b::T, potential::AbstractVector) where T
bs_a != bs_b && val_a + sum(k->readbit(bs_a, k) < readbit(bs_b, k) ? potential[k] : zero(T), 1:length(potential)) <= val_b
end
function worse_than(bs_a::Integer, bs_b::Integer, val_a::T, val_b::T, ::Nothing) where T
bs_a != bs_b && val_a <= val_b && (bs_b & bs_a) == bs_b
end
readbit(bs::Integer, k::Integer) = (bs >> (k-1)) & 1
"""
is_independent_set(g::SimpleGraph, config)
Return true if `config` (a vector of boolean numbers as the mask of vertices) is an independent set of graph `g`.
"""
is_independent_set(g::SimpleGraph, config) = !any(e->config[e.src] == 1 && config[e.dst] == 1, edges(g))
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2299 | """
$TYPEDEF
The [Vertex matching](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/Matching/) problem.
Positional arguments
-------------------------------
* `graph` is the problem graph.
* `weights` are associated with the edges of the `graph`.
"""
struct Matching{WT<:Union{UnitWeight,Vector}} <: GraphProblem
graph::SimpleGraph{Int}
weights::WT
function Matching(g::SimpleGraph, weights::Union{UnitWeight, Vector}=UnitWeight())
@assert weights isa UnitWeight || length(weights) == ne(g)
new{typeof(weights)}(g, weights)
end
end
flavors(::Type{<:Matching}) = [0, 1]
energy_terms(gp::Matching) = [[minmax(src(s), dst(s))] for s in edges(gp.graph)] # edge tensors
energy_tensors(x::T, c::Matching) where T = [_pow.(Ref(x), get_weights(c, i)) for i=1:ne(c.graph)]
extra_terms(gp::Matching) = [[minmax(i, j) for j in neighbors(gp.graph, i)] for i in Graphs.vertices(gp.graph)]
extra_tensors(::Type{T}, gp::Matching) where T = [match_tensor(T, degree(gp.graph, i)) for i=1:nv(gp.graph)]
labels(gp::Matching) = getindex.(energy_terms(gp))
# weights interface
get_weights(c::Matching) = c.weights
get_weights(m::Matching, i::Int) = [0, m.weights[i]]
chweights(c::Matching, weights) = Matching(c.graph, weights)
function match_tensor(::Type{T}, n::Int) where T
t = zeros(T, fill(2, n)...)
for ci in CartesianIndices(t)
if sum(ci.I .- 1) <= 1
t[ci] = one(T)
end
end
return t
end
"""
is_matching(graph::SimpleGraph, config)
Returns true if `config` is a valid matching on `graph`, and `false` if a vertex is double matched.
`config` is a vector of boolean variables, which has one to one correspondence with `edges(graph)`.
"""
function is_matching(g::SimpleGraph, config)
@assert ne(g) == length(config)
edges_mask = zeros(Bool, nv(g))
for (e, c) in zip(edges(g), config)
if !iszero(c)
if edges_mask[e.src]
@debug "Vertex $(e.src) is double matched!"
return false
end
if edges_mask[e.dst]
@debug "Vertex $(e.dst) is double matched!"
return false
end
edges_mask[e.src] = true
edges_mask[e.dst] = true
end
end
return true
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2550 | """
$TYPEDEF
The [cutting](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/MaxCut/) problem.
Positional arguments
-------------------------------
* `graph` is the problem graph.
* `edge_weights` are associated with the edges of the `graph`.
* `vertex_weights` are associated with the vertices of the `graph`.
"""
struct MaxCut{WT1<:Union{UnitWeight, Vector},WT2<:Union{ZeroWeight, Vector}} <: GraphProblem
graph::SimpleGraph{Int}
edge_weights::WT1
vertex_weights::WT2
function MaxCut(g::SimpleGraph,
edge_weights::Union{UnitWeight, Vector}=UnitWeight(),
vertex_weights::Union{ZeroWeight, Vector}=ZeroWeight())
@assert edge_weights isa UnitWeight || length(edge_weights) == ne(g)
@assert vertex_weights isa ZeroWeight || length(vertex_weights) == nv(g)
new{typeof(edge_weights), typeof(vertex_weights)}(g, edge_weights, vertex_weights)
end
end
flavors(::Type{<:MaxCut}) = [0, 1]
# first `ne` indices are for edge weights, last `nv` indices are for vertex weights.
energy_terms(gp::MaxCut) = [[[minmax(e.src,e.dst)...] for e in Graphs.edges(gp.graph)]...,
[[v] for v in Graphs.vertices(gp.graph)]...]
energy_tensors(x::T, c::MaxCut) where T = [[maxcutb(_pow.(Ref(x), get_weights(c, i))...) for i=1:ne(c.graph)]...,
[Ref(x) .^ get_weights(c, i+ne(c.graph)) for i=1:nv(c.graph)]...]
extra_terms(::MaxCut) = Vector{Int}[]
extra_tensors(::Type{T}, ::MaxCut) where T = Array{T}[]
labels(gp::MaxCut) = [1:nv(gp.graph)...]
# weights interface
get_weights(c::MaxCut) = [[c.edge_weights[i] for i=1:ne(c.graph)]..., [c.vertex_weights[i] for i=1:nv(c.graph)]...]
get_weights(gp::MaxCut, i::Int) = i <= ne(gp.graph) ? [0, gp.edge_weights[i]] : [0, gp.vertex_weights[i-ne(gp.graph)]]
chweights(c::MaxCut, weights) = MaxCut(c.graph, weights[1:ne(c.graph)], weights[ne(c.graph)+1:end])
function maxcutb(a, b)
return [a b; b a]
end
"""
cut_size(g::SimpleGraph, config; edge_weights=UnitWeight(), vertex_weights=ZeroWeight())
Compute the cut size for the vertex configuration `config` (an iterator).
"""
function cut_size(g::SimpleGraph, config; edge_weights=UnitWeight(), vertex_weights=ZeroWeight())
size = zero(promote_type(eltype(vertex_weights), eltype(edge_weights)))
for (i, e) in enumerate(edges(g))
size += (config[e.src] != config[e.dst]) * edge_weights[i]
end
for v in vertices(g)
size += config[v] * vertex_weights[v]
end
return size
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1861 | """
$TYPEDEF
The [maximal independent set](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/MaximalIS/) problem. In the constructor, `weights` are the weights of vertices.
Positional arguments
-------------------------------
* `graph` is the problem graph.
* `weights` are associated with the vertices of the `graph`.
"""
struct MaximalIS{WT<:Union{UnitWeight, Vector}} <: GraphProblem
graph::SimpleGraph
weights::WT
function MaximalIS(g::SimpleGraph, weights::Union{UnitWeight, Vector}=UnitWeight())
@assert weights isa UnitWeight || length(weights) == nv(g)
new{typeof(weights)}(g, weights)
end
end
flavors(::Type{<:MaximalIS}) = [0, 1]
energy_terms(gp::MaximalIS) = [[Graphs.neighbors(gp.graph, v)..., v] for v in Graphs.vertices(gp.graph)]
energy_tensors(x::T, c::MaximalIS) where T = [maximal_independent_set_tensor(_pow.(Ref(x), get_weights(c, i))..., degree(c.graph, i)+1) for i=1:nv(c.graph)]
extra_terms(::MaximalIS) = Vector{Int}[]
extra_tensors(::Type{T}, ::MaximalIS) where T = Array{T}[]
labels(gp::MaximalIS) = [1:nv(gp.graph)...]
# weights interface
get_weights(c::MaximalIS) = c.weights
get_weights(gp::MaximalIS, i::Int) = [0, gp.weights[i]]
chweights(c::MaximalIS, weights) = MaximalIS(c.graph, weights)
function maximal_independent_set_tensor(a::T, b::T, d::Int) where T
t = zeros(T, fill(2, d)...)
for i = 2:1<<(d-1)
t[i] = a
end
t[1<<(d-1)+1] = b
return t
end
"""
is_maximal_independent_set(g::SimpleGraph, config)
Return true if `config` (a vector of boolean numbers as the mask of vertices) is a maximal independent set of graph `g`.
"""
is_maximal_independent_set(g::SimpleGraph, config) = !any(e->config[e.src] == 1 && config[e.dst] == 1, edges(g)) && all(w->config[w] == 1 || any(v->!iszero(config[v]), neighbors(g, w)), Graphs.vertices(g)) | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 6834 | """
$TYPEDEF
The open pit mining problem.
This problem can be solved in polynomial time with the pseudoflow algorithm.
Positional arguments
-------------------------------
* `rewards` is a matrix of rewards.
* `blocks` are the locations of the blocks.
Example
-----------------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> rewards = [-4 -7 -7 -17 -7 -26;
0 39 -7 -7 -4 0;
0 0 1 8 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0];
julia> gp = GenericTensorNetwork(OpenPitMining(rewards));
julia> res = solve(gp, SingleConfigMax())[]
(21.0, ConfigSampler{12, 1, 1}(111000100000))ₜ
julia> is_valid_mining(rewards, res.c.data)
true
julia> print_mining(rewards, res.c.data)
-4 -7 -7 -17 -7 -26
◼ 39 -7 -7 -4 ◼
◼ ◼ 1 8 ◼ ◼
◼ ◼ ◼ ◼ ◼ ◼
◼ ◼ ◼ ◼ ◼ ◼
◼ ◼ ◼ ◼ ◼ ◼
```
You will the the mining is printed as green in an colored REPL.
"""
struct OpenPitMining{ET} <: GraphProblem
rewards::Matrix{ET}
blocks::Vector{Tuple{Int,Int}} # non-zero locations
function OpenPitMining(rewards::Matrix{ET}, blocks::Vector{Tuple{Int,Int}}) where ET
for (i, j) in blocks
checkbounds(rewards, i, j)
end
new{ET}(rewards, blocks)
end
end
function OpenPitMining(rewards::Matrix{ET}) where ET
# compute block locations
blocks = Tuple{Int,Int}[]
for i=1:size(rewards, 1), j=i:size(rewards,2)-i+1
push!(blocks, (i,j))
end
OpenPitMining(rewards, blocks)
end
function mining_tensor(::Type{T}) where T
t = ones(T,2,2)
t[2,1] = zero(T) # first one is mined, but the second one is not mined.
return t
end
flavors(::Type{<:OpenPitMining}) = [0, 1]
energy_terms(gp::OpenPitMining) = [[r] for r in gp.blocks]
energy_tensors(x::T, c::OpenPitMining) where T = [_pow.(Ref(x), get_weights(c, i)) for i=1:length(c.blocks)]
function extra_terms(gp::OpenPitMining)
depends = Pair{Tuple{Int,Int},Tuple{Int,Int}}[]
for i=1:size(gp.rewards, 1), j=i:size(gp.rewards,2)-i+1
if i!=1
push!(depends, (i,j)=>(i-1,j-1))
push!(depends, (i,j)=>(i-1,j))
push!(depends, (i,j)=>(i-1,j+1))
end
end
return [[dep.first, dep.second] for dep in depends]
end
extra_tensors(::Type{T}, gp::OpenPitMining) where T = [mining_tensor(T) for _ in extra_terms(gp)]
labels(gp::OpenPitMining) = gp.blocks
# weights interface
get_weights(c::OpenPitMining) = [c.rewards[b...] for b in c.blocks]
get_weights(gp::OpenPitMining, i::Int) = [0, gp.rewards[gp.blocks[i]...]]
function chweights(c::OpenPitMining, weights)
rewards = copy(c.rewards)
for (w, b) in zip(weights, c.blocks)
rewards[b...] = w
end
OpenPitMining(rewards, c.blocks)
end
"""
is_valid_mining(rewards::AbstractMatrix, config)
Return true if `config` (a boolean mask for the feasible region) is a valid mining of `rewards`.
"""
function is_valid_mining(rewards::AbstractMatrix, config)
blocks = get_blocks(rewards)
assign = Dict(zip(blocks, config))
for block in blocks
if block[1] != 1 && !iszero(assign[block])
if iszero(assign[(block[1]-1, block[2]-1)]) ||
iszero(assign[(block[1]-1, block[2])]) ||
iszero(assign[(block[1]-1, block[2]+1)])
return false
end
end
end
return true
end
function get_blocks(rewards)
blocks = Tuple{Int,Int}[]
for i=1:size(rewards, 1), j=i:size(rewards,2)-i+1
push!(blocks, (i,j))
end
return blocks
end
"""
print_mining(rewards::AbstractMatrix, config)
Printing the mining solution in a colored REPL.
"""
function print_mining(rewards::AbstractMatrix{T}, config) where T
k = 0
for i=1:size(rewards, 1)
for j=1:size(rewards, 2)
if j >= i && j <= size(rewards,2)-i+1
k += 1
if T <: Integer
str = @sprintf " %6i " rewards[i,j]
else
str = @sprintf " %6.2F " rewards[i,j]
end
if iszero(config[k])
printstyled(str; color = :red)
else
printstyled(str; color = :green)
end
else
str = @sprintf " %6s " "◼"
printstyled(str; color = :black)
end
end
println()
end
end
function _open_pit_mining_branching!(rewards::AbstractMatrix{T}, mask::AbstractMatrix{Bool}, setmask::AbstractMatrix{Bool}, idx::Int) where T
# find next
idx < 1 && return zero(T)
i, j = divrem(idx-1, size(mask, 2)) .+ 1 # row-wise!
while i > j || size(mask, 1)-i+1 < j || setmask[i, j] # skip not allowed or already decided
idx -= 1
idx < 1 && return zero(T)
i, j = divrem(idx-1, size(mask, 2)) .+ 1 # row-wise!
end
if rewards[i, j] < 0 # do not mine!
setmask[i, j] = true
return _open_pit_mining_branching!(rewards, mask, setmask, idx-1)
else
_mask = copy(mask)
_setmask = copy(setmask)
# CASE 1: try mine current block
# set mask
reward0 = set_recur!(mask, setmask, rewards, i, j)
reward1 = _open_pit_mining_branching!(rewards, mask, setmask, idx-1) + reward0
# CASE 1: try do not mine current block
# unset mask
_setmask[i, j] = true
reward2 = _open_pit_mining_branching!(rewards, _mask, _setmask, idx-1)
# choose the right branch
if reward2 > reward1
copyto!(mask, _mask)
copyto!(setmask, _setmask)
return reward2
else
return reward1
end
end
end
function set_recur!(mask, setmask, rewards::AbstractMatrix{T}, i, j) where T
reward = zero(T)
for k=1:i
start = max(1, j-(i-k))
stop = min(size(mask, 2), j+(i-k))
@inbounds for l=start:stop
if !setmask[k,l]
mask[k,l] = true
setmask[k,l] = true
reward += rewards[k,l]
end
end
end
return reward
end
"""
open_pit_mining_branching(rewards::AbstractMatrix)
Solve the open pit mining problem with the naive branching algorithm.
NOTE: open pit mining can be solved in polynomial time, but this one runs in exponential time.
"""
function open_pit_mining_branching(rewards::AbstractMatrix{T}) where T
idx = length(rewards)
mask = falses(size(rewards))
rewards = _open_pit_mining_branching!(rewards, mask, falses(size(rewards)), idx)
return rewards, mask
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3427 | """
$TYPEDEF
The [binary paint shop problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/PaintShop/).
Positional arguments
-------------------------------
* `sequence` is a vector of symbols, each symbol is associated with a color.
* `isfirst` is a vector of boolean numbers, indicating whether the symbol is the first appearance in the sequence.
Examples
-------------------------------
One can encode the paint shop problem `abaccb` as the following
```jldoctest; setup=:(using GenericTensorNetworks)
julia> syms = collect("abaccb");
julia> pb = GenericTensorNetwork(PaintShop(syms));
julia> solve(pb, SizeMin())[]
2.0ₜ
julia> solve(pb, ConfigsMin())[].c.data
2-element Vector{StaticBitVector{3, 1}}:
100
011
```
In our definition, we find the maximum number of unchanged color in this sequence, i.e. (n-1) - (minimum number of color changes)
In the output of maximum configurations, the two configurations are defined on 5 bonds i.e. pairs of (i, i+1), `0` means color changed, while `1` means color not changed.
If we denote two "colors" as `r` and `b`, then the optimal painting is `rbbbrr` or `brrrbb`, both change the colors twice.
"""
struct PaintShop{LT} <: GraphProblem
sequence::Vector{LT}
isfirst::Vector{Bool}
function PaintShop(sequence::AbstractVector{T}) where T
@assert all(l->count(==(l), sequence)==2, sequence)
n = length(sequence)
isfirst = [findfirst(==(sequence[i]), sequence) == i for i=1:n]
new{eltype(sequence)}(sequence, isfirst)
end
end
function paint_shop_from_pairs(pairs::AbstractVector{Tuple{Int,Int}})
n = length(pairs)
@assert sort!(vcat(collect.(pairs)...)) == collect(1:2n)
sequence = zeros(Int, 2*n)
@inbounds for i=1:n
sequence[pairs[i]] .= i
end
return PaintShop(sequence)
end
flavors(::Type{<:PaintShop}) = [0, 1]
energy_terms(gp::PaintShop) = [[gp.sequence[i], gp.sequence[i+1]] for i in 1:length(gp.sequence)-1]
energy_tensors(x::T, c::PaintShop) where T = [flip_labels(paintshop_bond_tensor(_pow.(Ref(x), get_weights(c, i))...), c.isfirst[i], c.isfirst[i+1]) for i=1:length(c.sequence)-1]
extra_terms(::PaintShop{LT}) where LT = Vector{LT}[]
extra_tensors(::Type{T}, ::PaintShop) where T = Array{T}[]
labels(gp::PaintShop) = unique(gp.sequence)
# weights interface
get_weights(c::PaintShop) = UnitWeight()
get_weights(::PaintShop, i::Int) = [0, 1]
chweights(c::PaintShop, weights) = c
function paintshop_bond_tensor(a::T, b::T) where T
m = T[a b; b a]
return m
end
function flip_labels(m, if1, if2)
m = if1 ? m : m[[2,1],:]
m = if2 ? m : m[:,[2,1]]
return m
end
"""
num_paint_shop_color_switch(sequence::AbstractVector, coloring)
Returns the number of color switches.
"""
function num_paint_shop_color_switch(sequence::AbstractVector, coloring)
return count(i->coloring[i] != coloring[i+1], 1:length(sequence)-1)
end
"""
paint_shop_coloring_from_config(p::PaintShop, config)
Returns a valid painting from the paint shop configuration (given by the configuration solvers).
The `config` is a sequence of 0 and 1, where 0 means painting the first appearence of a car in blue, 1 otherwise.
"""
function paint_shop_coloring_from_config(p::PaintShop{LT}, config) where {LT}
d = Dict{LT,Bool}(zip(labels(p), config))
return map(1:length(p.sequence)) do i
p.isfirst[i] ? d[p.sequence[i]] : ~d[p.sequence[i]]
end
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 5312 | """
BoolVar{T}
BoolVar(name, neg)
Boolean variable for constructing CNF clauses.
"""
struct BoolVar{T}
name::T
neg::Bool
end
BoolVar(name) = BoolVar(name, false)
function Base.show(io::IO, b::BoolVar)
b.neg && print(io, "¬")
print(io, b.name)
end
"""
CNFClause{T}
CNFClause(vars)
A clause in [`CNF`](@ref), its value is the logical or of `vars`, where `vars` is a vector of [`BoolVar`](@ref).
"""
struct CNFClause{T}
vars::Vector{BoolVar{T}}
end
function Base.show(io::IO, b::CNFClause)
print(io, join(string.(b.vars), " ∨ "))
end
Base.:(==)(x::CNFClause, y::CNFClause) = x.vars == y.vars
"""
CNF{T}
CNF(clauses)
Boolean expression in [conjunctive normal form](https://en.wikipedia.org/wiki/Conjunctive_normal_form).
`clauses` is a vector of [`CNFClause`](@ref), if and only if all clauses are satisfied, this CNF is satisfied.
Example
------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> @bools x y z
julia> cnf = (x ∨ y) ∧ (¬y ∨ z)
(x ∨ y) ∧ (¬y ∨ z)
julia> satisfiable(cnf, Dict([:x=>true, :y=>false, :z=>true]))
true
julia> satisfiable(cnf, Dict([:x=>false, :y=>false, :z=>true]))
false
```
"""
struct CNF{T}
clauses::Vector{CNFClause{T}}
end
function Base.show(io::IO, c::CNF)
print(io, join(["($k)" for k in c.clauses], " ∧ "))
end
Base.:(==)(x::CNF, y::CNF) = x.clauses == y.clauses
Base.length(x::CNF) = length(x.clauses)
"""
¬(var::BoolVar)
Negation of a boolean variables of type [`BoolVar`](@ref).
"""
¬(var::BoolVar{T}) where T = BoolVar(var.name, ~var.neg)
"""
∨(vars...)
Logical `or` applied on [`BoolVar`](@ref) and [`CNFClause`](@ref).
Returns a [`CNFClause`](@ref).
"""
∨(var::BoolVar{T}, vars::BoolVar{T}...) where T = CNFClause([var, vars...])
∨(c::CNFClause{T}, var::BoolVar{T}) where T = CNFClause([c.vars..., var])
∨(c::CNFClause{T}, d::CNFClause{T}) where T = CNFClause([c.vars..., d.vars...])
∨(var::BoolVar{T}, c::CNFClause) where T = CNFClause([var, c.vars...])
"""
∧(vars...)
Logical `and` applied on [`CNFClause`](@ref) and [`CNF`](@ref).
Returns a new [`CNF`](@ref).
"""
∧(c::CNFClause{T}, cs::CNFClause{T}...) where T = CNF([c, cs...])
∧(c::CNFClause{T}, cs::CNF{T}) where T = CNF([c, cs.clauses...])
∧(cs::CNF{T}, c::CNFClause{T}) where T = CNF([cs.clauses..., c])
∧(cs::CNF{T}, ds::CNF{T}) where T = CNF([cs.clauses..., ds.clauses...])
"""
@bools(syms::Symbol...)
Create some boolean variables of type [`BoolVar`](@ref) in current scope that can be used in create a [`CNF`](@ref).
Example
------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> @bools x y z
julia> (x ∨ y) ∧ (¬y ∨ z)
(x ∨ y) ∧ (¬y ∨ z)
```
"""
macro bools(syms::Symbol...)
esc(Expr(:block, [:($s = $BoolVar($(QuoteNode(s)))) for s in syms]..., nothing))
end
"""
$TYPEDEF
The [satisfiability](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/Satisfiability/) problem.
Positional arguments
-------------------------------
* `cnf` is a conjunctive normal form ([`CNF`](@ref)) for specifying the satisfiability problems.
* `weights` are associated with clauses.
Examples
-------------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> @bools x y z a b c
julia> c1 = x ∨ ¬y
x ∨ ¬y
julia> c2 = c ∨ (¬a ∨ b)
c ∨ ¬a ∨ b
julia> c3 = (z ∨ ¬a) ∨ y
z ∨ ¬a ∨ y
julia> c4 = (c ∨ z) ∨ ¬b
c ∨ z ∨ ¬b
julia> cnf = (c1 ∧ c4) ∧ (c2 ∧ c3)
(x ∨ ¬y) ∧ (c ∨ z ∨ ¬b) ∧ (c ∨ ¬a ∨ b) ∧ (z ∨ ¬a ∨ y)
julia> gp = GenericTensorNetwork(Satisfiability(cnf));
julia> solve(gp, SizeMax())[]
4.0ₜ
```
"""
struct Satisfiability{T,WT<:Union{UnitWeight, Vector}} <: GraphProblem
cnf::CNF{T}
weights::WT
function Satisfiability(cnf::CNF{T}, weights::WT=UnitWeight()) where {T, WT}
@assert weights isa UnitWeight || length(weights) == length(cnf) "weights size inconsistent! should be $(length(cnf)), got: $(length(weights))"
new{T, typeof(weights)}(cnf, weights)
end
end
flavors(::Type{<:Satisfiability}) = [0, 1] # false, true
energy_terms(gp::Satisfiability) = [[getfield.(c.vars, :name)...] for c in gp.cnf.clauses]
energy_tensors(x::T, c::Satisfiability) where T = [tensor_for_clause(c.cnf.clauses[i], _pow.(Ref(x), get_weights(c, i))...) for i=1:length(c.cnf.clauses)]
extra_terms(::Satisfiability{T}) where T = Vector{T}[]
extra_tensors(::Type{T}, c::Satisfiability) where T = Array{T}[]
labels(gp::Satisfiability) = unique!(vcat(energy_terms(gp)...))
# weights interface
get_weights(c::Satisfiability) = c.weights
get_weights(s::Satisfiability, i::Int) = [0, s.weights[i]]
chweights(c::Satisfiability, weights) = Satisfiability(c.cnf, weights)
"""
satisfiable(cnf::CNF, config::AbstractDict)
Returns true if an assignment of variables satisfies a [`CNF`](@ref).
"""
function satisfiable(cnf::CNF{T}, config::AbstractDict{T}) where T
all(x->satisfiable(x, config), cnf.clauses)
end
function satisfiable(c::CNFClause{T}, config::AbstractDict{T}) where T
any(x->satisfiable(x, config), c.vars)
end
function satisfiable(v::BoolVar{T}, config::AbstractDict{T}) where T
config[v.name] == ~v.neg
end
function tensor_for_clause(c::CNFClause{T}, a, b) where T
n = length(c.vars)
map(ci->any(i->~c.vars[i].neg == ci[i], 1:n) ? b : a, Iterators.product([[0, 1] for i=1:n]...))
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2516 | """
$TYPEDEF
The [set covering problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/SetCovering/).
Positional arguments
-------------------------------
* `sets` is a vector of vectors, each set is associated with a weight specified in `weights`.
* `weights` are associated with sets.
Examples
-------------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> sets = [[1, 2, 5], [1, 3], [2, 4], [3, 6], [2, 3, 6]]; # each set is a vertex
julia> gp = GenericTensorNetwork(SetCovering(sets));
julia> res = solve(gp, ConfigsMin())[]
(3.0, {10110, 10101})ₜ
```
"""
struct SetCovering{ET, WT<:Union{UnitWeight, Vector}} <: GraphProblem
sets::Vector{Vector{ET}}
weights::WT
function SetCovering(sets::Vector{Vector{ET}}, weights::Union{UnitWeight, Vector}=UnitWeight()) where {ET}
@assert weights isa UnitWeight || length(weights) == length(sets)
new{ET, typeof(weights)}(sets, weights)
end
end
flavors(::Type{<:SetCovering}) = [0, 1]
energy_terms(gp::SetCovering) = [[i] for i=1:length(gp.sets)]
energy_tensors(x::T, c::SetCovering) where T = [misv(_pow.(Ref(x), get_weights(c, i))) for i=1:length(c.sets)]
function extra_terms(sc::SetCovering)
elements, count = cover_count(sc.sets)
return [count[e] for e in elements]
end
extra_tensors(::Type{T}, cfg::SetCovering) where T = [cover_tensor(T, ix) for ix in extra_terms(cfg)]
labels(gp::SetCovering) = [1:length(gp.sets)...]
# weights interface
get_weights(c::SetCovering) = c.weights
get_weights(gp::SetCovering, i::Int) = [0, gp.weights[i]]
chweights(c::SetCovering, weights) = SetCovering(c.sets, weights)
function cover_tensor(::Type{T}, set_indices::AbstractVector{Int}) where T
n = length(set_indices)
t = ones(T, fill(2, n)...)
t[1] = zero(T)
return t
end
function cover_count(sets)
elements = vcat(sets...)
count = Dict{eltype(elements), Vector{Int}}()
for (iset, set) in enumerate(sets)
for e in set
if haskey(count, e)
push!(count[e], iset)
else
count[e] = [iset]
end
end
end
return elements, count
end
"""
is_set_covering(sets::AbstractVector, config)
Return true if `config` (a vector of boolean numbers as the mask of sets) is a set covering of `sets`.
"""
function is_set_covering(sets::AbstractVector, config)
insets = sets[(!iszero).(config)]
return length(unique!(vcat(insets...))) == length(unique!(vcat(sets...)))
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2185 | """
$TYPEDEF
The [set packing problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/SetPacking/), a generalization of independent set problem to hypergraphs.
Positional arguments
-------------------------------
* `sets` is a vector of vectors, each set is associated with a weight specified in `weights`.
* `weights` are associated with sets.
Examples
-------------------------------
```jldoctest; setup=:(using GenericTensorNetworks, Random; Random.seed!(2))
julia> sets = [[1, 2, 5], [1, 3], [2, 4], [3, 6], [2, 3, 6]]; # each set is a vertex
julia> gp = GenericTensorNetwork(SetPacking(sets));
julia> res = solve(gp, ConfigsMax())[]
(2.0, {00110, 10010, 01100})ₜ
```
"""
struct SetPacking{ET,WT<:Union{UnitWeight, Vector}} <: GraphProblem
sets::Vector{Vector{ET}}
weights::WT
function SetPacking(sets::Vector{Vector{ET}}, weights::Union{UnitWeight, Vector}=UnitWeight()) where {ET}
@assert weights isa UnitWeight || length(weights) == length(sets)
new{ET, typeof(weights)}(sets, weights)
end
end
flavors(::Type{<:SetPacking}) = [0, 1]
energy_terms(gp::SetPacking) = [[i] for i=1:length(gp.sets)]
energy_tensors(x::T, c::SetPacking) where T = [misv(_pow.(Ref(x), get_weights(c, i))) for i=1:length(c.sets)]
extra_terms(gp::SetPacking) = [[i,j] for i=1:length(gp.sets),j=1:length(gp.sets) if j>i && !isempty(gp.sets[i] ∩ gp.sets[j])]
extra_tensors(::Type{T}, gp::SetPacking) where T = [misb(T, length(ix)) for ix in extra_terms(gp)]
labels(gp::SetPacking) = [1:length(gp.sets)...]
# weights interface
get_weights(c::SetPacking) = c.weights
get_weights(gp::SetPacking, i::Int) = [0, gp.weights[i]]
chweights(c::SetPacking, weights) = SetPacking(c.sets, weights)
"""
is_set_packing(sets::AbstractVector, config)
Return true if `config` (a vector of boolean numbers as the mask of sets) is a set packing of `sets`.
"""
function is_set_packing(sets::AbstractVector{ST}, config) where ST
d = Dict{eltype(ST), Int}()
for i=1:length(sets)
if !iszero(config[i])
for e in sets[i]
d[e] = get(d, e, 0) + 1
end
end
end
return all(isone, values(d))
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 4325 | """
$(TYPEDEF)
SpinGlass(n, cliques; weights=UnitWeight())
SpinGlass(graph::SimpleGraph, J=UnitWeight(), h=ZeroWeight())
The [spin-glass](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/SpinGlass/) problem.
Positional arguments
-------------------------------
* `n` is the number of spins.
* `cliques` is a vector of cliques, each being a vector of vertices (integers). For simple graph, it is a vector of edges.
* `weights` are associated with the cliques.
"""
struct SpinGlass{WT<:Union{UnitWeight, Vector}} <: GraphProblem
n::Int
cliques::Vector{Vector{Int}}
weights::WT
function SpinGlass(n::Int, cliques::AbstractVector, weights::Union{UnitWeight, Vector}=UnitWeight())
clqs = collect(collect.(cliques))
@assert weights isa UnitWeight || length(weights) == length(clqs)
@assert all(c->all(b->1<=b<=n, c), cliques) "vertex index out of bound 1-$n, got: $cliques"
return new{typeof(weights)}(n, clqs, weights)
end
end
function SpinGlass(graph::SimpleGraph, J::Union{UnitWeight, Vector}, h::Union{ZeroWeight, Vector}=ZeroWeight())
J_ = J isa UnitWeight ? fill(1, ne(graph)) : J
h_ = h isa ZeroWeight ? fill(0, nv(graph)) : h
@assert length(J_) == ne(graph) "length of J must be equal to the number of edges $(ne(graph)), got: $(length(J_))"
@assert length(h_) == nv(graph) "length of h must be equal to the number of vertices $(nv(graph)), got: $(length(h_))"
SpinGlass(nv(graph), [[[src(e), dst(e)] for e in edges(graph)]..., [[i] for i in 1:nv(graph)]...], [J_..., h_...])
end
function spin_glass_from_matrix(M::AbstractMatrix, h::AbstractVector)
g = SimpleGraph((!iszero).(M))
J = [M[e.src, e.dst] for e in edges(g)]
return SpinGlass(g, J, h)
end
flavors(::Type{<:SpinGlass}) = [0, 1]
# first `ne` indices are for edge weights, last `n` indices are for vertex weights.
energy_terms(gp::SpinGlass) = gp.cliques
energy_tensors(x::T, c::SpinGlass) where T = [clique_tensor(length(c.cliques[i]), _pow.(Ref(x), get_weights(c, i))...) for i=1:length(c.cliques)]
extra_terms(sg::SpinGlass) = [[i] for i=1:sg.n]
extra_tensors(::Type{T}, c::SpinGlass) where T = [[one(T), one(T)] for i=1:c.n]
labels(gp::SpinGlass) = collect(1:gp.n)
# weights interface
get_weights(c::SpinGlass) = c.weights
get_weights(gp::SpinGlass, i::Int) = [-gp.weights[i], gp.weights[i]]
chweights(c::SpinGlass, weights) = SpinGlass(c.n, c.cliques, weights)
function clique_tensor(rank, a::T, b::T) where T
res = zeros(T, fill(2, rank)...)
for i=0:(1<<rank-1)
res[i+1] = (count_ones(i) % 2) == 1 ? a : b
end
return res
end
"""
spinglass_energy(g::SimpleGraph, config; J, h=ZeroWeight())
spinglass_energy(cliques::AbstractVector{Vector{Int}}, config; weights=UnitWeight())
spinglass_energy(sg::SpinGlass, config)
Compute the spin glass state energy for the vertex configuration `config`.
In the configuration, the spin ↑ is mapped to configuration 0, while spin ↓ is mapped to configuration 1.
Let ``G=(V,E)`` be the input graph, the hamiltonian is
```math
H = \\sum_{ij \\in E} J_{ij} s_i s_j + \\sum_{i \\in V} h_i s_i,
```
where ``s_i \\in \\{-1, 1\\}`` stands for spin ↓ and spin ↑.
In the hypergraph case, the hamiltonian is
```math
H = \\sum_{c \\in C} w_c \\prod_{i \\in c} s_i,
```
where ``C`` is the set of cliques, and ``w_c`` is the weight of the clique ``c``.
"""
function spinglass_energy(cliques::AbstractVector{Vector{Int}}, config; weights=UnitWeight())::Real
size = zero(eltype(weights))
@assert all(x->x == 0 || x == 1, config)
s = 1 .- 2 .* Int.(config) # 0 -> spin 1, 1 -> spin -1
for (i, spins) in enumerate(cliques)
size += prod(s[spins]) * weights[i]
end
return size
end
function spinglass_energy(g::SimpleGraph, config; J, h=ZeroWeight())
eng = zero(promote_type(eltype(J), eltype(h)))
# NOTE: cast to Int to avoid using unsigned :nt
s = 1 .- 2 .* Int.(config) # 0 -> spin 1, 1 -> spin -1
# coupling terms
for (i, e) in enumerate(edges(g))
eng += (s[e.src] * s[e.dst]) * J[i]
end
# onsite terms
for (i, v) in enumerate(vertices(g))
eng += s[v] * h[i]
end
return eng
end
function spinglass_energy(sg::SpinGlass, config)
spinglass_energy(sg.cliques, config; weights=sg.weights)
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 8903 | """
GraphProblem
The abstract base type of graph problems.
"""
abstract type GraphProblem end
function generate_tensors(x::T, m::GraphProblem) where T
tensors = [energy_tensors(x, m)..., extra_tensors(T, m)...]
ixs = [energy_terms(m)..., extra_terms(m)...]
return add_labels!(tensors, ixs, labels(m))
end
function rawcode(problem::GraphProblem; openvertices=())
ixs = [energy_terms(problem)..., extra_terms(problem)...]
LT = eltype(eltype(ixs))
return DynamicEinCode(ixs, collect(LT, openvertices)) # labels for edge tensors
end
struct UnitWeight end
Base.getindex(::UnitWeight, i) = 1
Base.eltype(::UnitWeight) = Int
struct ZeroWeight end
Base.getindex(::ZeroWeight, i) = 0
Base.eltype(::ZeroWeight) = Int
"""
$TYPEDEF
GenericTensorNetwork(problem::GraphProblem; openvertices=(), fixedvertices=Dict(), optimizer=GreedyMethod())
The generic tensor network that generated from a [`GraphProblem`](@ref).
Positional arguments
-------------------------------
* `problem` is the graph problem.
* `code` is the tensor network contraction code.
* `fixedvertices` is a dictionary specifying the fixed dimensions.
"""
struct GenericTensorNetwork{CFG, CT, LT}
problem::CFG
code::CT
fixedvertices::Dict{LT,Int}
end
function GenericTensorNetwork(problem::GraphProblem; openvertices=(), fixedvertices=Dict(), optimizer=GreedyMethod())
rcode = rawcode(problem; openvertices)
code = _optimize_code(rcode, uniformsize_fix(rcode, nflavor(problem), fixedvertices), optimizer, MergeVectors())
return GenericTensorNetwork(problem, code, Dict{labeltype(code),Int}(fixedvertices))
end
function generate_tensors(x::T, tn::GenericTensorNetwork) where {T}
ixs = getixsv(tn.code)
isempty(ixs) && return Array{T}[]
tensors = generate_tensors(x, tn.problem)
return select_dims(tensors, ixs, fixedvertices(tn))
end
######## Interfaces for graph problems ##########
"""
get_weights(problem::GraphProblem[, i::Int]) -> Vector
get_weights(problem::GenericTensorNetwork[, i::Int]) -> Vector
The weights for the `problem` or the weights for the degree of freedom specified by the `i`-th term if a second argument is provided.
Weights are associated with [`energy_terms`](@ref) in the graph problem.
In graph polynomial, integer weights can be the exponents.
"""
function get_weights end
get_weights(gp::GenericTensorNetwork) = get_weights(gp.problem)
get_weights(gp::GenericTensorNetwork, i::Int) = get_weights(gp.problem, i)
"""
chweights(problem::GraphProblem, weights) -> GraphProblem
chweights(problem::GenericTensorNetwork, weights) -> GenericTensorNetwork
Change the weights for the `problem` and return a new problem instance.
Weights are associated with [`energy_terms`](@ref) in the graph problem.
In graph polynomial, integer weights can be the exponents.
"""
function chweights end
chweights(gp::GenericTensorNetwork, weights) = GenericTensorNetwork(chweights(gp.problem, weights), gp.code, gp.fixedvertices)
"""
labels(problem::GraphProblem) -> Vector
labels(problem::GenericTensorNetwork) -> Vector
The labels of a graph problem is defined as the degrees of freedoms in the graph problem.
e.g. for the maximum independent set problems, they are the indices of vertices: 1, 2, 3...,
while for the max cut problem, they are the edges.
"""
labels(gp::GenericTensorNetwork) = labels(gp.problem)
"""
energy_terms(problem::GraphProblem) -> Vector
energy_terms(problem::GenericTensorNetwork) -> Vector
The energy terms of a graph problem is defined as the tensor labels that carrying local energies (or weights) in the graph problem.
"""
function energy_terms end
energy_terms(gp::GenericTensorNetwork) = energy_terms(gp.problem)
"""
extra_terms(problem::GraphProblem) -> Vector
extra_terms(problem::GenericTensorNetwork) -> Vector
The extra terms of a graph problem is defined as the tensor labels that not carrying local energies (or weights) in the graph problem.
"""
function extra_terms end
extra_terms(gp::GenericTensorNetwork) = extra_terms(gp.problem)
"""
fixedvertices(tnet::GenericTensorNetwork) -> Dict
Returns the fixed vertices in the graph problem, which is a dictionary specifying the fixed dimensions.
"""
fixedvertices(gtn::GenericTensorNetwork) = gtn.fixedvertices
"""
flavors(::Type{<:GraphProblem}) -> Vector
flavors(::Type{<:GenericTensorNetwork}) -> Vector
It returns a vector of integers as the flavors of a degree of freedom.
Its size is the same as the degree of freedom on a single vertex/edge.
"""
flavors(::GT) where GT<:GraphProblem = flavors(GT)
flavors(::GenericTensorNetwork{GT}) where GT<:GraphProblem = flavors(GT)
"""
nflavor(::Type{<:GraphProblem}) -> Int
nflavor(::Type{<:GenericTensorNetwork}) -> Int
nflavor(::GT) where GT<:GraphProblem -> Int
nflavor(::GenericTensorNetwork{GT}) where GT<:GraphProblem -> Int
Bond size is equal to the number of flavors.
"""
nflavor(::Type{GT}) where GT = length(flavors(GT))
nflavor(::Type{GenericTensorNetwork{GT}}) where GT = nflavor(GT)
nflavor(::GT) where GT<:GraphProblem = nflavor(GT)
nflavor(::GenericTensorNetwork{GT}) where GT<:GraphProblem = nflavor(GT)
"""
generate_tensors(func, problem::GenericTensorNetwork)
Generate a vector of tensors as the inputs of the tensor network contraction code `problem.code`.
`func` is a function to customize the tensors.
`func(symbol)` returns a vector of elements, the length of which is same as the number of flavors.
Example
--------------------------
The following code gives your the maximum independent set size
```jldoctest
julia> using Graphs, GenericTensorNetworks
julia> gp = GenericTensorNetwork(IndependentSet(smallgraph(:petersen)));
julia> getixsv(gp.code)
25-element Vector{Vector{Int64}}:
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
⋮
[3, 8]
[4, 5]
[4, 9]
[5, 10]
[6, 8]
[6, 9]
[7, 9]
[7, 10]
[8, 10]
julia> gp.code(GenericTensorNetworks.generate_tensors(Tropical(1.0), gp)...)
0-dimensional Array{Tropical{Float64}, 0}:
4.0ₜ
```
"""
function generate_tensors end
# requires field `code`
include("IndependentSet.jl")
include("MaximalIS.jl")
include("MaxCut.jl")
include("Matching.jl")
include("Coloring.jl")
include("PaintShop.jl")
include("Satisfiability.jl")
include("DominatingSet.jl")
include("SetPacking.jl")
include("SetCovering.jl")
include("OpenPitMining.jl")
include("SpinGlass.jl")
# forward the time, space and readwrite complexity
OMEinsum.contraction_complexity(gp::GenericTensorNetwork) = contraction_complexity(gp.code, uniformsize(gp.code, nflavor(gp)))
# the following two interfaces will be deprecated
OMEinsum.timespace_complexity(gp::GenericTensorNetwork) = timespace_complexity(gp.code, uniformsize(gp.code, nflavor(gp)))
OMEinsum.timespacereadwrite_complexity(gp::GenericTensorNetwork) = timespacereadwrite_complexity(gp.code, uniformsize(gp.code, nflavor(gp)))
# contract the graph tensor network
function contractx(gp::GenericTensorNetwork, x; usecuda=false)
@debug "generating tensors for x = `$x` ..."
xs = generate_tensors(x, gp)
@debug "contracting tensors ..."
if usecuda
gp.code([togpu(x) for x in xs]...)
else
gp.code(xs...)
end
end
function uniformsize_fix(code, dim, fixedvertices)
size_dict = uniformsize(code, dim)
for key in keys(fixedvertices)
size_dict[key] = 1
end
return size_dict
end
# multiply labels vectors to the generate tensor.
add_labels!(tensors::AbstractVector{<:AbstractArray}, ixs, labels) = tensors
const SetPolyNumbers{T} = Union{Polynomial{T}, TruncatedPoly{K,T} where K, CountingTropical{TV,T} where TV} where T<:AbstractSetNumber
function add_labels!(tensors::AbstractVector{<:AbstractArray{T}}, ixs, labels) where T <: Union{AbstractSetNumber, SetPolyNumbers, ExtendedTropical{K,T} where {K,T<:SetPolyNumbers}}
for (t, ix) in zip(tensors, ixs)
for (dim, l) in enumerate(ix)
index = findfirst(==(l), labels)
v = [_onehotv(T, index, k-1) for k=1:size(t, dim)]
t .*= reshape(v, ntuple(j->dim==j ? length(v) : 1, ndims(t)))
end
end
return tensors
end
# select dimensions from tensors
# `tensors` is a vector of tensors,
# `ixs` is the tensor labels for `tensors`.
# `fixedvertices` is a dictionary specifying the fixed dimensions, check [`fixedvertices`](@ref)
function select_dims(tensors::AbstractVector{<:AbstractArray{T}}, ixs, fixedvertices::AbstractDict) where T
isempty(fixedvertices) && return tensors
map(tensors, ixs) do t, ix
dims = map(ixi->ixi ∉ keys(fixedvertices) ? Colon() : (fixedvertices[ixi]+1:fixedvertices[ixi]+1), ix)
t[dims...]
end
end
_pow(x, i) = x^i
function _pow(x::LaurentPolynomial{BS,X}, i) where {BS,X}
if i >= 0
return x^i
else
@assert length(x.coeffs) == 1
return LaurentPolynomial(x.coeffs .^ i, x.order[]*i)
end
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 9337 | using GenericTensorNetworks, Test, OMEinsum
using GenericTensorNetworks.Mods, Polynomials, TropicalNumbers
using Graphs, Random
using GenericTensorNetworks: StaticBitVector
using LinearAlgebra
@testset "truncated poly" begin
p1 = TruncatedPoly((2,2,1), 2.0)
p2 = TruncatedPoly((2,3,9), 4.0)
x = Polynomial([2, 2, 1])
@test Polynomial(p1) == x
@test LaurentPolynomial(p1) == x
y = Polynomial([0, 0, 2, 3, 9])
r1 = p1 + p2
r2 = p2 + p1
r3 = x + y
@test r1.coeffs == r2.coeffs == (r3.coeffs[end-2:end]...,)
q1 = p1 * p2
q2 = p2 * p1
q3 = x * y
@test q1.coeffs == q2.coeffs == (q3.coeffs[end-2:end]...,)
r1 = p1 + p1
r3 = x + x
@test r1.coeffs == (r3.coeffs[end-2:end]...,)
r1 = p1 * p1
r3 = x * x
@test r1.coeffs == (r3.coeffs[end-2:end]...,)
end
@testset "arithematics" begin
Random.seed!(2)
for (a, b, c) in [
(TropicalF64(2), TropicalF64(8), TropicalF64(9)),
(CountingTropicalF64(2, 8), CountingTropicalF64(8, 9), CountingTropicalF64(9, 2)),
(Mod{17}(2), Mod{17}(8), Mod{17}(9)),
(Polynomial([0,1,2,3.0]), Polynomial([3,2.0]), Polynomial([1,7.0])),
(Max2Poly(1,2,3.0), Max2Poly(3,2,2.0), Max2Poly(4,7,1.0)),
(TruncatedPoly((1,2,3),3.0), TruncatedPoly((7,3,2),2.0), TruncatedPoly((1,4,7),1.0)),
(TropicalF64(5), TropicalF64(3), TropicalF64(-9)),
(ExtendedTropical{2}(Tropical.([2.2,3.1])), ExtendedTropical{2}(Tropical.([-1.0, 4.0])), ExtendedTropical{2}(Tropical.([-Inf, 0.6]))),
(CountingTropicalF64(5, 3), CountingTropicalF64(3, 9), CountingTropicalF64(-3, 2)),
(CountingTropical(5.0, ConfigSampler(StaticBitVector(rand(Bool, 10)))), CountingTropical(3.0, ConfigSampler(StaticBitVector(rand(Bool, 10)))), CountingTropical(-3.0, ConfigSampler(StaticBitVector(rand(Bool, 10))))),
(CountingTropical(5.0, ConfigEnumerator([StaticBitVector(rand(Bool, 10)) for j=1:3])), CountingTropical(3.0, ConfigEnumerator([StaticBitVector(rand(Bool, 10)) for j=1:4])), CountingTropical(-3.0, ConfigEnumerator([StaticBitVector(rand(Bool, 10)) for j=1:5]))),
(ConfigEnumerator([StaticBitVector(rand(Bool, 10)) for j=1:3]), ConfigEnumerator([StaticBitVector(rand(Bool, 10)) for j=1:4]), ConfigEnumerator([StaticBitVector(rand(Bool, 10)) for j=1:5])),
(SumProductTree(GenericTensorNetworks.SUM, [SumProductTree(StaticBitVector(rand(Bool, 10))) for j=1:2]...),
SumProductTree(GenericTensorNetworks.SUM, [SumProductTree(StaticBitVector(rand(Bool, 10))) for j=1:2]...),
SumProductTree(GenericTensorNetworks.SUM, [SumProductTree(StaticBitVector(rand(Bool, 10))) for j=1:2]...)
),
(SumProductTree(GenericTensorNetworks.PROD, [SumProductTree(StaticBitVector(rand(Bool, 10))) for j=1:2]...),
SumProductTree(GenericTensorNetworks.PROD, [SumProductTree(StaticBitVector(rand(Bool, 10))) for j=1:2]...),
SumProductTree(GenericTensorNetworks.PROD, [SumProductTree(StaticBitVector(rand(Bool, 10))) for j=1:2]...)
),
(SumProductTree(GenericTensorNetworks.PROD, [SumProductTree(OnehotVec{10, 2}(rand(1:10), 1)) for j=1:2]...),
SumProductTree(GenericTensorNetworks.PROD, [SumProductTree(OnehotVec{10, 2}(rand(1:10), 1)) for j=1:2]...),
SumProductTree(GenericTensorNetworks.PROD, [SumProductTree(OnehotVec{10, 2}(rand(1:10), 1)) for j=1:2]...)
),
(SumProductTree(StaticBitVector(rand(Bool, 10))),
SumProductTree(StaticBitVector(rand(Bool, 10))),
SumProductTree(StaticBitVector(rand(Bool, 10))),
),
]
@test is_commutative_semiring(a, b, c)
@test false * a == zero(a)
@test true * a == a
@test a * false == zero(a)
@test a * true == a
end
# the following tests are for Polynomial + ConfigEnumerator
a = ConfigEnumerator([StaticBitVector(trues(10)) for j=1:3])
@test 1 * a == a
@test 0 * a == zero(a)
@test a[1] == StaticBitVector(trues(10))
@test copy(a) == a
@test length.(a) == [10, 10, 10]
@test map(x->length(x), a) == [10, 10, 10]
# the following tests are for Polynomial + ConfigEnumerator
a = SumProductTree(StaticBitVector(trues(10)))
@test 1 * a == a
@test 0 * a == zero(a)
@test copy(a) == a
@test length(a) == 1
@test length(a + a) == 2
@test length(a * a) == 1
print((a+a) * a)
b = a + a
@test GenericTensorNetworks.num_nodes(b * b) == 3
a = ConfigSampler(StaticBitVector(rand(Bool, 10)))
@test 1 * a == a
@test 0 * a == zero(a)
println(Max2Poly{Float64,Float64}(1, 1, 1))
@test abs(Mod{5}(2)) == Mod{5}(2)
@test Mod{5}(12) < Mod{5}(8)
end
@testset "powers" begin
x = ConfigEnumerator([bv"00111"])
y = 2.0
@test x ^ 0 == one(x)
@test Base.literal_pow(^, x, Val(2.0)) == x
@test x ^ y == x
x = SumProductTree(bv"00111")
@test x ^ 0 == one(x)
@test Base.literal_pow(^, x, Val(2.0)) == x
@test x ^ y == x
x = ConfigSampler(bv"00111")
@test x ^ 0 == one(x)
@test Base.literal_pow(^, x, Val(2.0)) == x
@test x ^ y == x
x = ExtendedTropical{3}(Tropical.([1.0, 2.0, 3.0]))
@test x ^ 1 == x
@test x ^ 0 == one(x)
@test x ^ 1.0 == x
@test x ^ 0.0 == one(x)
@test x ^ 2 == ExtendedTropical{3}(Tropical.([2.0, 4.0, 6.0]))
@test Base.literal_pow(^, x, Val(2.0)) == ExtendedTropical{3}(Tropical.([2.0, 4.0, 6.0]))
@test Base.literal_pow(^, x, Val(2.0)) == x ^ y
# truncated poly
x = TruncatedPoly((2,3), 5)
@test x ^ 2 == TruncatedPoly((12,9), 10)
@test_throws ErrorException x ^ -2
x = TruncatedPoly((0.0,3.0), 5)
@test x ^ 2 == TruncatedPoly((0,9), 10)
@test x ^ -2 == TruncatedPoly((0.0,3^-2), -10)
end
@testset "push coverage" begin
@test abs(Mod{5}(2)) == Mod{5}(2)
@test one(ConfigSampler(bv"11100")) == ConfigSampler(bv"00000")
T = SumProductTree{OnehotVec{5,2}}
@test collect(one(T(GenericTensorNetworks.ZERO))) == collect(SumProductTree(bv"00000"))
@test iszero(copy(T(GenericTensorNetworks.ZERO)))
x = SumProductTree(bv"00111")
@test copy(x) == x
@test copy(x) !== x
@test !iszero(x)
y = x + x
@test copy(y) == y
@test copy(y) !== y
@test !iszero(y)
println((x * x) * zero(x))
end
@testset "Truncated Tropical" begin
# +
a = ExtendedTropical{3}(Tropical.([1,2,3]))
b = ExtendedTropical{3}(Tropical.([4,5,6]))
c = ExtendedTropical{3}(Tropical.([0,1,2]))
@test a + b == ExtendedTropical{3}(Tropical.([4,5,6]))
@test b + a == ExtendedTropical{3}(Tropical.([4,5,6]))
@test c + a == ExtendedTropical{3}(Tropical.([2,2,3]))
@test a + c == ExtendedTropical{3}(Tropical.([2,2,3]))
# *
function naive_mul(a, b)
K = length(a)
return sort!(vec([x*y for x in a, y in b]))[end-K+1:end]
end
d = ExtendedTropical{3}(Tropical.([0,1,20]))
@test naive_mul(a.orders, b.orders) == (a * b).orders
@test naive_mul(b.orders, a.orders) == (b * a).orders
@test naive_mul(a.orders, d.orders) == (a * d).orders
@test naive_mul(d.orders, a.orders) == (d * a).orders
@test naive_mul(d.orders, d.orders) == (d * d).orders
for i=1:20
a = ExtendedTropical{100}(Tropical.(sort!(randn(100))))
b = ExtendedTropical{100}(Tropical.(sort!(randn(100))))
@test naive_mul(a.orders, b.orders) == (a * b).orders
end
end
@testset "count geq" begin
A = collect(1:10)
B = collect(2:2:20)
low = 20
c, _ = GenericTensorNetworks.count_geq(A, B, 1, low, false)
@test c == count(x->x>=low, vec([a*b for a in A, b in B]))
res = similar(A, c)
@test sort!(GenericTensorNetworks.collect_geq!(res, A, B, 1, low)) == sort!(filter(x->x>=low, vec([a*b for a in A, b in B])))
end
# check the correctness of sampling
@testset "generate samples" begin
Random.seed!(2)
g = smallgraph(:petersen)
gp = GenericTensorNetwork(IndependentSet(g))
t = solve(gp, ConfigsAll(tree_storage=true))[]
cs = solve(gp, ConfigsAll())[]
@test length(t) == 76
samples = generate_samples(t, 10000)
counts = zeros(5)
for sample in samples
counts[count_ones(sample)+1] += 1
end
@test isapprox(counts, [1,10,30,30,5] .* 10000 ./ 76, rtol=0.05)
hd1 = hamming_distribution(samples, samples) |> normalize
hd2 = hamming_distribution(cs, cs) |> normalize
@test isapprox(hd1, hd2, atol=0.01)
end
@testset "LaurentPolynomial" begin
@test GenericTensorNetworks._x(LaurentPolynomial{Float64, :x}; invert=false) == GenericTensorNetworks._x(Polynomial{Float64, :x}; invert=false)
end
@testset "readers" begin
x = TruncatedPoly((2,3), 5)
@test read_size_count(x) == [4=>2, 5=>3]
s4 = [StaticBitVector(trues(10)) for j=1:3]
s5 = [StaticBitVector(trues(10)) for j=1:4]
x = TruncatedPoly((ConfigEnumerator(s4), ConfigEnumerator(s5)), 5)
@test read_size_config(x) == [4=>s4, 5=>s5]
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1025 | using Test, GenericTensorNetworks
using GenericTensorNetworks: statictrues, staticfalses, StaticBitVector, onehotv
@testset "static bit vector" begin
@test statictrues(StaticBitVector{3,1}) == trues(3)
@test staticfalses(StaticBitVector{3,1}) == falses(3)
@test_throws BoundsError statictrues(StaticBitVector{3,1})[4]
#@test (@inbounds statictrues(StaticBitVector{3,1})[4]) == 0
x = rand(Bool, 131)
y = rand(Bool, 131)
a = StaticBitVector(x)
b = StaticBitVector(y)
a2 = BitVector(x)
b2 = BitVector(y)
for op in [|, &, ⊻]
@test op(a, b) == op.(a2, b2)
end
@test onehotv(StaticBitVector{133,3}, 5) == (x = falses(133); x[5]=true; x)
@test [StaticElementVector(3, [2,1,0,1])...] == [2,1,0,1]
bl = rand(0:2,100)
@test [StaticElementVector(3, bl)...] == bl
bl = rand(1:15,100)
xl = StaticElementVector(16, bl)
@test typeof(xl) == StaticElementVector{100,4,7}
@test [xl...] == bl
@test bv"110_111" == StaticBitVector([1,1,0,1,1,1])
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1703 | using Test, OMEinsum, GenericTensorNetworks, TropicalNumbers, Random
using GenericTensorNetworks: cached_einsum, generate_masktree, masked_einsum, CacheTree, uniformsize, bounding_contract
@testset "cached einsum" begin
xs = map(x->Tropical.(x), [randn(2,2), randn(2), randn(2,2), randn(2,2), randn(2,2)])
code = ein"((ij,j),jk, kl), ii->kli"
size_dict = uniformsize(code, 2)
c = cached_einsum(code, xs, size_dict)
@test c.content == code(xs...)
mt = generate_masktree(AllConfigs{1}(), code, c, rand(Bool,2,2,2), size_dict)
@test mt isa CacheTree{Bool}
y = masked_einsum(code, xs, mt, size_dict)
@test y isa AbstractArray
end
@testset "bounding contract" begin
for seed in 1:100
Random.seed!(seed)
xs = map(x->TropicalF64.(x), [rand(1:5,2,2), rand(1:5,2), rand(1:5,2,2), rand(1:5,2,2), rand(1:5,2,2)])
code = ein"((ij,j),jk, kl), ii->kli"
y1 = code(xs...)
y2 = bounding_contract(AllConfigs{1}(), code, xs, BitArray(ones(Bool,2,2,2)), xs)
@test y1 ≈ y2
end
rawcode = GenericTensorNetwork(IndependentSet(random_regular_graph(10, 3)); optimizer=nothing).code
optcode = GenericTensorNetwork(IndependentSet(random_regular_graph(10, 3)); optimizer=GreedyMethod()).code
xs = map(OMEinsum.getixs(rawcode)) do ix
length(ix)==1 ? GenericTensorNetworks.misv([one(TropicalF64), TropicalF64(1.0)]) : GenericTensorNetworks.misb(TropicalF64)
end
y1 = rawcode(xs...)
y2 = bounding_contract(AllConfigs{1}(), rawcode, xs, BitArray(fill(true)), xs)
@test y1 ≈ y2
y1 = optcode(xs...)
y2 = bounding_contract(AllConfigs{1}(), optcode, xs, BitArray(fill(true)), xs)
@test y1 ≈ y2
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3235 | using GenericTensorNetworks, Test, Graphs
using OMEinsum
using TropicalNumbers: CountingTropicalF64
using GenericTensorNetworks: _onehotv, _x, sampler_type, set_type, best_solutions, best2_solutions, solutions, all_solutions, bestk_solutions, AllConfigs, SingleConfig, max_size, max_size_count
@testset "Config types" begin
T = sampler_type(CountingTropical{Float32}, 5, 2)
x = one(T)
@test x.n === 0f0
@test x.c.data == falses(5)
x = zero(T)
@test x.n === Float32(-Inf)
@test x.c.data == trues(5)
x = _onehotv(T, 2, 1)
@test x.n === 0f0
@test x.c.data == Bool[0,1,0,0,0]
T = set_type(CountingTropical{Float32}, 5, 2)
x = one(T)
@test x.n === 0f0
@test length(x.c.data) == 1 && x.c.data[1] == falses(5)
x = zero(T)
@test x.n === Float32(-Inf)
@test length(x.c.data) == 0
x = _onehotv(T, 2, 1)
@test x.n === 0f0
@test length(x.c.data) == 1 && x.c.data[1] == Bool[0,1,0,0,0]
x = _onehotv(T, 2, 0)
@test x.c.data[1].data[1] == 0
end
@testset "enumerating" begin
problem = IndependentSet(smallgraph(:petersen))
rawcode = GenericTensorNetwork(problem, optimizer=nothing)
@test rawcode.code isa DynamicEinCode
optcode = GenericTensorNetwork(problem, optimizer=GreedyMethod())
for code in [rawcode, optcode]
res0 = max_size(code)
_, res1 = max_size_count(code)
res2 = best_solutions(code; all=true)[]
res3 = solutions(code, CountingTropical{Float64}; all=false)[]
res4 = solutions(code, CountingTropical{Float64}; all=true)[]
@test res0 == res2.n == res3.n == res4.n
@test res1 == length(res2.c) == length(res4.c)
@test res3.c.data ∈ res2.c.data
@test res3.c.data ∈ res4.c.data
res5 = best_solutions(code; all=false)[]
@test res5.n == res0
@test res5.c.data ∈ res2.c.data
res6 = best2_solutions(code; all=true)[]
res6_ = bestk_solutions(code, 2)[]
res7 = all_solutions(code)[]
idp = graph_polynomial(code, Val(:finitefield))[]
@test all(x->x ∈ res7.coeffs[end-1].data, res6.coeffs[1].data)
@test all(x->x ∈ res7.coeffs[end].data, res6.coeffs[2].data)
@test all(x->x ∈ res7.coeffs[end-1].data, res6_.coeffs[1].data)
@test all(x->x ∈ res7.coeffs[end].data, res6_.coeffs[2].data)
for (i, (s, c)) in enumerate(zip(res7.coeffs, idp.coeffs))
@test length(s) == c
@test all(x->count_ones(x)==(i-1), s.data)
end
end
end
@testset "configs bug fix" begin
subgraph = let
g = SimpleGraph(5)
vertices = "cdefg"
for (w, v) in ["cd", "ce", "cf", "de", "ef", "fg"]
add_edge!(g, findfirst(==(w), vertices), findfirst(==(v), vertices))
end
g
end
problem = GenericTensorNetwork(IndependentSet(subgraph), openvertices=[1,4,5])
res1 = solve(problem, SizeMax(), T=Float64)
@test res1 == Tropical.(reshape([1, 1, 2, -Inf, 2, 2, -Inf, -Inf], 2, 2, 2))
res2 = solve(problem, CountingMax(); T=Float64)
res3 = solve(problem, ConfigsMax(; bounded=true); T=Float64)
@test getfield.(res2, :n) == getfield.(res1, :n)
@test getfield.(res3, :n) == getfield.(res1, :n)
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2687 | using CUDA, Random
using LinearAlgebra: mul!
using GenericTensorNetworks, Test
using Graphs
CUDA.allowscalar(false)
@testset "cuda patch" begin
for T in [Tropical{Float64}, CountingTropical{Float64,Float64}]
a = T.(CUDA.randn(4, 4))
b = T.(CUDA.randn(4))
for A in [transpose(a), a, transpose(b)]
for B in [transpose(a), a, b]
if !(size(A) == (1,4) && size(B) == (4,))
res0 = Array(A) * Array(B)
res1 = A * B
res2 = mul!(CUDA.zeros(T, size(res0)...), A, B, true, false)
@test Array(res1) ≈ res0
@test Array(res2) ≈ res0
end
end
end
end
end
@testset "cuda functions" begin
g = Graphs.smallgraph("petersen")
item(x::AbstractArray) = Array(x)[]
#optimizer = TreeSA(ntrials=1)
optimizer = GreedyMethod()
gp = GenericTensorNetwork(IndependentSet(g); optimizer=optimizer)
@test contraction_complexity(gp).sc == 4
@test timespacereadwrite_complexity(gp)[2] == 4
@test timespace_complexity(gp)[2] == 4
res1 = solve(gp, SizeMax(); usecuda=true) |> item
res2 = solve(gp, CountingAll(); usecuda=true) |> item
res3 = solve(gp, CountingMax(Single); usecuda=true) |> item
res4 = solve(gp, CountingMax(2); usecuda=true) |> item
res5 = solve(gp, GraphPolynomial(; method = :polynomial))[]
res6 = solve(gp, SingleConfigMax(); usecuda=true) |> item
res7 = solve(gp, ConfigsMax(;bounded=false))[]
res10 = solve(gp, GraphPolynomial(method=:fft); usecuda=true) |> item
res11 = solve(gp, GraphPolynomial(method=:finitefield); usecuda=true) |> item
res12 = solve(gp, SingleConfigMax(; bounded=true); usecuda=true) |> item
res13 = solve(gp, ConfigsMax(;bounded=true))[]
res14 = solve(gp, CountingMax(3); usecuda=true) |> item
res18 = solve(gp, PartitionFunction(0.0); usecuda=true) |> item
@test res1.n == 4
@test res2 == 76
@test res3.n == 4 && res3.c == 5
@test res4.maxorder == 4 && res4.coeffs[1] == 30 && res4.coeffs[2]==5
@test res6.c.data ∈ res7.c.data
@test res10 ≈ res5
@test res11 == res5
@test res12.c.data ∈ res13.c.data
@test res14.maxorder == 4 && res14.coeffs[1]==30 && res14.coeffs[2] == 30 && res14.coeffs[3]==5
@test res18 ≈ res2
end
@testset "spinglass" begin
g = Graphs.smallgraph("petersen")
gp = GenericTensorNetwork(SpinGlass(g, UnitWeight()))
usecuda=true
@test solve(gp, CountingMax(); usecuda) isa CuArray
gp2 = GenericTensorNetwork(SpinGlass(g, UnitWeight()); openvertices=(2,))
@test solve(gp2, CountingMax(); usecuda) isa CuArray
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1843 | using GenericTensorNetworks, Graphs, Test
@testset "save load" begin
M = 10
fname = tempname()
m = ConfigEnumerator([StaticBitVector(rand(Bool, 300)) for i=1:M])
bm = GenericTensorNetworks.plain_matrix(m)
rm = GenericTensorNetworks.raw_matrix(m)
m1 = GenericTensorNetworks.from_raw_matrix(rm; bitlength=300, nflavors=2)
m2 = GenericTensorNetworks.from_plain_matrix(bm; nflavors=2)
@test m1 == m
@test m2 == m
save_configs(fname, m; format=:binary)
@test_throws ErrorException load_configs("_test.bin"; format=:binary)
ma = load_configs(fname; format=:binary, bitlength=300, nflavors=2)
@test ma == m
fname = tempname()
save_configs(fname, m; format=:text)
mb = load_configs(fname; format=:text, nflavors=2)
@test mb == m
M = 10
m = ConfigEnumerator([StaticElementVector(3, rand(0:2, 300)) for i=1:M])
bm = GenericTensorNetworks.plain_matrix(m)
rm = GenericTensorNetworks.raw_matrix(m)
m1 = GenericTensorNetworks.from_raw_matrix(rm; bitlength=300, nflavors=3)
m2 = GenericTensorNetworks.from_plain_matrix(bm; nflavors=3)
@test m1 == m
@test m2 == m
@test Matrix(m) == bm
@test Vector(m.data[1]) == bm[:,1]
fname = tempname()
save_configs(fname, m; format=:binary)
@test_throws ErrorException load_configs(fname; format=:binary)
ma = load_configs(fname; format=:binary, bitlength=300, nflavors=3)
@test ma == m
fname = tempname()
save_configs(fname, m; format=:text)
mb = load_configs(fname; format=:text, nflavors=3)
@test mb == m
end
@testset "save load tree" begin
fname = tempname()
tree = solve(GenericTensorNetwork(IndependentSet(smallgraph(:petersen))), ConfigsAll(; tree_storage=true))[]
save_sumproduct(fname, tree)
ma = load_sumproduct(fname)
@test ma == tree
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2242 | using GenericTensorNetworks, Test, OMEinsum
using GenericTensorNetworks.Mods, Polynomials, TropicalNumbers
using Graphs, Random
using GenericTensorNetworks: StaticBitVector, graph_polynomial
@testset "bond and vertex tensor" begin
@test GenericTensorNetworks.misb(TropicalF64) == [TropicalF64(0) TropicalF64(0); TropicalF64(0) TropicalF64(-Inf)]
@test GenericTensorNetworks.misv([one(TropicalF64), TropicalF64(2.0)]) == [TropicalF64(0), TropicalF64(2.0)]
end
@testset "graph generator" begin
g = diagonal_coupled_graph(trues(3, 3))
@test ne(g) == 20
g = diagonal_coupled_graph((x = trues(3, 3); x[2,2]=0; x))
@test ne(g) == 12
@test length(GenericTensorNetworks.labels(GenericTensorNetwork(IndependentSet(g)).code)) == 8
end
@testset "independence_polynomial" begin
Random.seed!(2)
g = random_regular_graph(10, 3)
tn = GenericTensorNetwork(IndependentSet(g))
p1 = graph_polynomial(tn, Val(:fitting))[]
p2 = graph_polynomial(tn, Val(:polynomial))[]
p3 = graph_polynomial(tn, Val(:fft))[]
p4 = graph_polynomial(tn, Val(:finitefield))[]
p5 = graph_polynomial(tn, Val(:finitefield); max_iter=1)[]
p8 = solve(tn, GraphPolynomial(; method=:laurent))[]
tn9 = GenericTensorNetwork(IndependentSet(g, fill(-1, 10)))
p9 = solve(tn9, GraphPolynomial(; method=:polynomial))[]
tn10 = GenericTensorNetwork(IndependentSet(g, rand([1,-1], 10)))
p10 = solve(tn10, GraphPolynomial(; method=:laurent))[]
@test p1 ≈ p2
@test p1 ≈ p3
@test p1 ≈ p4
@test p1 ≈ p5
@test p1 ≈ p8
@test p1 ≈ GenericTensorNetworks.invert_polynomial(p9)
@test sum(p10.coeffs) == sum(p1.coeffs)
# test overflow
g = random_regular_graph(120, 3)
gp = GenericTensorNetwork(IndependentSet(g), optimizer=TreeSA(; ntrials=1))
p6 = graph_polynomial(gp, Val(:polynomial))[]
p7 = graph_polynomial(gp, Val(:finitefield))[]
@test p6.coeffs ≈ p7.coeffs
end
@testset "open indices" begin
g = SimpleGraph(3)
for (i,j) in [(1,2), (2,3)]
add_edge!(g, i, j)
end
tn = GenericTensorNetwork(IndependentSet(g); openvertices=(1,3))
m1 = solve(tn, GraphPolynomial())
m2 = solve(tn, GraphPolynomial(;method=:polynomial))
@test m1 == m2
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 463 | using GenericTensorNetworks, Test, Graphs
@testset "special graphs" begin
g = random_square_lattice_graph(10, 10, 0.5)
@test nv(g) == 50
g = random_diagonal_coupled_graph(10, 10, 0.5)
@test nv(g) == 50
g = unit_disk_graph([(0.1, 0.2), (0.2, 0.3), (1.2, 1.4)], 1.0)
@test ne(g) == 1
@test nv(g) == 3
end
@testset "line graph" begin
g = smallgraph(:petersen)
lg = line_graph(g)
@test nv(lg) == 15
@test ne(lg) == 45
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 13648 | using GenericTensorNetworks
using Graphs, Test, Random
@testset "independent set problem" begin
g = Graphs.smallgraph("petersen")
for optimizer in (GreedyMethod(), TreeSA(ntrials=1))
Random.seed!(3)
gp = GenericTensorNetwork(IndependentSet(g); optimizer=optimizer)
@test contraction_complexity(gp).sc == 4
@test timespacereadwrite_complexity(gp)[2] == 4
@test timespace_complexity(gp)[2] == 4
res1 = solve(gp, SizeMax())[]
res2 = solve(gp, CountingAll())[]
res3 = solve(gp, CountingMax(Single))[]
res4 = solve(gp, CountingMax(2))[]
res5 = solve(gp, GraphPolynomial(; method = :polynomial))[]
res5b = solve(gp, GraphPolynomial(; method = :laurent))[]
res6 = solve(gp, SingleConfigMax())[]
res7 = solve(gp, ConfigsMax(;bounded=false))[]
res8 = solve(gp, ConfigsMax(2; bounded=false))[]
res9 = solve(gp, ConfigsAll())[]
res10 = solve(gp, GraphPolynomial(method=:fft))[]
res11 = solve(gp, GraphPolynomial(method=:finitefield))[]
res12 = solve(gp, SingleConfigMax(; bounded=true))[]
res13 = solve(gp, ConfigsMax(;bounded=true))[]
res14 = solve(gp, CountingMax(3))[]
res15 = solve(gp, ConfigsMax(3))[]
res16 = solve(gp, ConfigsMax(2; bounded=true))[]
res17 = solve(gp, ConfigsMax(3; bounded=true))[]
res18 = solve(gp, PartitionFunction(0.0))[]
@test res1.n == 4 == read_size(res1)
@test res2 == 76
res3n, res3c = read_size_count(res3)
@test read_count(res3) == res3c
@test read_size(res3) == res3n
@test res3.n == 4 == res3n && res3.c == 5 == res3c
res4nc = read_size_count(res4)
@test read_size(res4) == getfield.(res4nc, :first)
@test read_count(res4) == getfield.(res4nc, :second)
@test res4.maxorder == 4 == res4nc[end].first && res4.coeffs[1] == 30 == res4nc[1].second && res4.coeffs[2]==5 == res4nc[2].second
@test read_size_count(res5) == [0=>1.0, 1=>10.0, 2=>30.0, 3=>30.0, 4=>5.0]
@test res5 == Polynomial([1.0, 10.0, 30, 30, 5])
@test read_size_count(res5b) == [0=>1.0, 1=>10.0, 2=>30.0, 3=>30.0, 4=>5.0]
@test read_size(res5b) == getfield.(read_size_count(res5), :first)
@test read_count(res5b) == getfield.(read_size_count(res5), :second)
@test res5b == LaurentPolynomial([1.0, 10.0, 30, 30, 5])
res6n, res6c = read_size_config(res6)
@test read_size(res6) == res6n
@test read_config(res6) == res6c
res7n, res7c = read_size_config(res7)
@test read_size(res7) == res7n
@test read_config(res7) == res7c
@test res6.c.data ∈ res7.c.data
@test res6n == res6n
@test res6c ∈ res7c
@test all(x->sum(x) == 4, res7.c.data)
res8nc = read_size_config(res8)
@test read_size(res8) == getfield.(res8nc, :first)
@test read_config(res8) == getfield.(res8nc, :second)
res8p = Polynomial(res8)
order = length(res8p.coeffs)
@test read_size(res8p)[order-1:order] == getfield.(res8nc, :first)
@test read_config(res8p)[order-1:order] == getfield.(res8nc, :second)
@test res8nc[1].second == res8.coeffs[1].data
@test all(x->sum(x) == 3, res8.coeffs[1].data) && all(x->sum(x) == 4, res8.coeffs[2].data) && length(res8.coeffs[1].data) == 30 && length(res8.coeffs[2].data) == 5
res9c = read_config(res9)
@test res9c == res9.data
@test length(unique(res9.data)) == 76 && all(c->is_independent_set(g, c), res9.data)
@test res10 ≈ res5
@test res11 == res5
res12n, res12c = read_size_config(res12)
@test res12n == res12.n
@test res12c == res12.c.data
@test res12.c.data ∈ res13.c.data
@test res13.c == res7.c
@test res14.maxorder == 4 && res14.coeffs[1]==30 && res14.coeffs[2] == 30 && res14.coeffs[3]==5
@test all(x->sum(x) == 2, res15.coeffs[1].data) && all(x->sum(x) == 3, res15.coeffs[2].data) && all(x->sum(x) == 4, res15.coeffs[3].data) &&
length(res15.coeffs[1].data) == 30 && length(res15.coeffs[2].data) == 30 && length(res15.coeffs[3].data) == 5
@test all(x->sum(x) == 3, res16.coeffs[1].data) && all(x->sum(x) == 4, res16.coeffs[2].data) && length(res16.coeffs[1].data) == 30 && length(res16.coeffs[2].data) == 5
@test all(x->sum(x) == 2, res17.coeffs[1].data) && all(x->sum(x) == 3, res17.coeffs[2].data) && all(x->sum(x) == 4, res17.coeffs[3].data) &&
length(res17.coeffs[1].data) == 30 && length(res17.coeffs[2].data) == 30 && length(res17.coeffs[3].data) == 5
@test res18 ≈ res2
end
end
@testset "slicing" begin
g = Graphs.smallgraph("petersen")
gp = GenericTensorNetwork(IndependentSet(g), optimizer=TreeSA(nslices=5, ntrials=1))
res1 = solve(gp, SizeMax())[]
res2 = solve(gp, CountingAll())[]
res3 = solve(gp, CountingMax(Single))[]
res4 = solve(gp, CountingMax(2))[]
res5 = solve(gp, GraphPolynomial(; method = :polynomial))[]
res6 = solve(gp, SingleConfigMax())[]
res7 = solve(gp, ConfigsMax(;bounded=false))[]
res8 = solve(gp, ConfigsMax(2; bounded=false))[]
res9 = solve(gp, ConfigsAll())[]
res10 = solve(gp, GraphPolynomial(method=:fft))[]
res11 = solve(gp, GraphPolynomial(method=:finitefield))[]
res12 = solve(gp, SingleConfigMax(; bounded=true))[]
res13 = solve(gp, ConfigsMax(;bounded=true))[]
res14 = solve(gp, CountingMax(3))[]
res15 = solve(gp, ConfigsMax(3))[]
res16 = solve(gp, ConfigsMax(2; bounded=true))[]
res17 = solve(gp, ConfigsMax(3; bounded=true))[]
@test res1.n == 4
@test res2 == 76
@test res3.n == 4 && res3.c == 5
@test res4.maxorder == 4 && res4.coeffs[1] == 30 && res4.coeffs[2]==5
@test res5 == Polynomial([1.0, 10.0, 30, 30, 5])
@test res6.c.data ∈ res7.c.data
@test all(x->sum(x) == 4, res7.c.data)
@test all(x->sum(x) == 3, res8.coeffs[1].data) && all(x->sum(x) == 4, res8.coeffs[2].data) && length(res8.coeffs[1].data) == 30 && length(res8.coeffs[2].data) == 5
@test length(unique(res9.data)) == 76 && all(c->is_independent_set(g, c), res9.data)
@test res10 ≈ res5
@test res11 == res5
@test res12.c.data ∈ res13.c.data
@test res13.c == res7.c
@test res14.maxorder == 4 && res14.coeffs[1]==30 && res14.coeffs[2] == 30 && res14.coeffs[3]==5
@test all(x->sum(x) == 2, res15.coeffs[1].data) && all(x->sum(x) == 3, res15.coeffs[2].data) && all(x->sum(x) == 4, res15.coeffs[3].data) &&
length(res15.coeffs[1].data) == 30 && length(res15.coeffs[2].data) == 30 && length(res15.coeffs[3].data) == 5
@test all(x->sum(x) == 3, res16.coeffs[1].data) && all(x->sum(x) == 4, res16.coeffs[2].data) && length(res16.coeffs[1].data) == 30 && length(res16.coeffs[2].data) == 5
@test all(x->sum(x) == 2, res17.coeffs[1].data) && all(x->sum(x) == 3, res17.coeffs[2].data) && all(x->sum(x) == 4, res17.coeffs[3].data) &&
length(res17.coeffs[1].data) == 30 && length(res17.coeffs[2].data) == 30 && length(res17.coeffs[3].data) == 5
end
@testset "Weighted" begin
g = Graphs.smallgraph("petersen")
gp = IndependentSet(g, collect(1:10)) |> GenericTensorNetwork
res1 = solve(gp, SizeMax())[]
@test res1 == Tropical(24.0)
res2 = solve(gp, CountingMax(Single))[]
@test res2 == CountingTropical(24.0, 1.0)
res2b = solve(gp, CountingMax(2))[]
@test res2b == Max2Poly(1.0, 1.0, 24.0)
res3 = solve(gp, SingleConfigMax(; bounded=false))[]
res3b = solve(gp, SingleConfigMax(; bounded=true))[]
@test res3 == res3b
@test sum(collect(res3.c.data) .* (1:10)) == 24.0
res4 = solve(gp, ConfigsMax(Single; bounded=false))[]
res4b = solve(gp, ConfigsMax(Single; bounded=true))[]
@test res4 == res4b
@test res4.c.data[] == res3.c.data
g = Graphs.smallgraph("petersen")
gp = IndependentSet(g, fill(0.5, 10)) |> GenericTensorNetwork
res5 = solve(gp, SizeMax(6))[]
@test res5.orders == Tropical.([3.0,4,4,4,4,4] ./ 2)
res6 = solve(gp, SingleConfigMax(6))[]
res6c = read_config(res6)
@test res6c == getfield.(getfield.(res6.orders, :c), :data)
@test all(enumerate(res6.orders)) do r
i, o = r
is_independent_set(g, o.c.data) && count_ones(o.c.data) == (i==1 ? 3 : 4)
end
end
@testset "tree storage" begin
g = smallgraph(:petersen)
gp = IndependentSet(g) |> GenericTensorNetwork
res1 = solve(gp, ConfigsAll(; tree_storage=true))[]
res2 = solve(gp, ConfigsAll(; tree_storage=false))[]
@test res1 isa SumProductTree && res2 isa ConfigEnumerator
@test length(res1) == length(res2)
@test Set(res2 |> collect) == Set(res1 |> collect)
res1 = solve(gp, ConfigsMax(; tree_storage=true))[]
res2 = solve(gp, ConfigsMax(; tree_storage=false))[].c
res1n, res1c = read_size_config(res1)
@test read_size(res1) == res1n
@test read_config(res1) == res1c
@test res1c == collect(res1.c)
@test res1.c isa SumProductTree && res2 isa ConfigEnumerator
@test length(res1.c) == length(res2)
@test Set(res2 |> collect) == Set(res1.c |> collect)
res1s = solve(gp, ConfigsMax(2; tree_storage=true))[]
res2s = solve(gp, ConfigsMax(2; tree_storage=false))[].coeffs
res1ncs = read_size_config(res1s)
@test length(res1ncs) == 2
@test res1ncs[1].second == collect(res1s.coeffs[1])
for (res1, res2) in zip(res1s.coeffs, res2s)
@test res1 isa SumProductTree && res2 isa ConfigEnumerator
@test length(res1) == length(res2)
@test Set(res2 |> collect) == Set(res1 |> collect)
end
res1 = solve(gp, ConfigsMin(; tree_storage=true))[]
res2 = solve(gp, ConfigsMin(; tree_storage=false))[].c
@test res1.c isa SumProductTree && res2 isa ConfigEnumerator
@test length(res1.c) == length(res2)
@test Set(res2 |> collect) == Set(res1.c |> collect)
res1s = solve(gp, ConfigsMin(2; tree_storage=true))[].coeffs
res2s = solve(gp, ConfigsMin(2; tree_storage=false))[].coeffs
for (res1, res2) in zip(res1s, res2s)
@test res1 isa SumProductTree && res2 isa ConfigEnumerator
@test length(res1) == length(res2)
@test Set(res2 |> collect) == Set(res1 |> collect)
end
end
@testset "memory estimation" begin
gp = IndependentSet(smallgraph(:petersen)) |> GenericTensorNetwork
for property in [
SizeMax(), SizeMin(), SizeMax(3), SizeMin(3), CountingMax(), CountingMin(), CountingMax(2), CountingMin(2),
ConfigsMax(;bounded=true), ConfigsMin(;bounded=true), ConfigsMax(2;bounded=true), ConfigsMin(2;bounded=true),
ConfigsMax(;bounded=false), ConfigsMin(;bounded=false), ConfigsMax(2;bounded=false), ConfigsMin(2;bounded=false), SingleConfigMax(;bounded=false), SingleConfigMin(;bounded=false),
CountingAll(), ConfigsAll(), SingleConfigMax(2), SingleConfigMin(2), SingleConfigMax(2; bounded=true), SingleConfigMin(2,bounded=true),
]
@show property
ET = GenericTensorNetworks.tensor_element_type(Float32, 10, 2, property)
@test eltype(solve(gp, property, T=Float32)) <: ET
@test estimate_memory(gp, property) isa Integer
end
@test GenericTensorNetworks.tensor_element_type(Float32, 10, 2, GraphPolynomial(method=:polynomial)) == Polynomial{Float32, :x}
@test GenericTensorNetworks.tensor_element_type(Float32, 10, 2, GraphPolynomial(method=:laurent)) == LaurentPolynomial{Float32, :x}
@test sizeof(GenericTensorNetworks.tensor_element_type(Float32, 10, 2, GraphPolynomial(method=:fitting))) == 4
@test sizeof(GenericTensorNetworks.tensor_element_type(Float32, 10, 2, GraphPolynomial(method=:fft))) == 8
@test sizeof(GenericTensorNetworks.tensor_element_type(Float64, 10, 2, GraphPolynomial(method=:finitefield))) == 4
@test GenericTensorNetworks.tensor_element_type(Float32, 10, 2, SingleConfigMax(;bounded=true)) == Tropical{Float32}
@test GenericTensorNetworks.tensor_element_type(Float32, 10, 2, SingleConfigMin(;bounded=true)) == Tropical{Float32}
@test estimate_memory(gp, SizeMax()) * 2 == estimate_memory(gp, CountingMax())
@test estimate_memory(gp, SizeMax()) == estimate_memory(gp, PartitionFunction(1.0))
@test estimate_memory(gp, SingleConfigMax(bounded=true)) > estimate_memory(gp, SingleConfigMax(bounded=false))
@test estimate_memory(gp, ConfigsMax(bounded=true)) == estimate_memory(gp, SingleConfigMax(bounded=false))
@test estimate_memory(gp, GraphPolynomial(method=:fitting); T=Float32) * 4 == estimate_memory(gp, GraphPolynomial(method=:fft))
@test estimate_memory(gp, GraphPolynomial(method=:finitefield)) * 10 == estimate_memory(gp, GraphPolynomial(method=:polynomial); T=Float32)
end
@testset "error on not solvable problems" begin
gp = GenericTensorNetwork(IndependentSet(smallgraph(:petersen), rand(1:3, 10)))
@test !GenericTensorNetworks.has_noninteger_weights(gp)
gp = GenericTensorNetwork(IndependentSet(smallgraph(:petersen), rand(10)))
@test GenericTensorNetworks.has_noninteger_weights(gp)
@test_throws ArgumentError solve(gp, GraphPolynomial())
@test_throws ArgumentError solve(gp, CountingMax(2))
@test solve(gp, CountingMax(Single)) isa Array
@test_throws ArgumentError solve(gp, ConfigsMax(2))
@test solve(gp, CountingMin(Single)) isa Array
@test_throws ArgumentError solve(gp, ConfigsMin(2))
@test solve(gp, ConfigsMax(Single)) isa Array
@test_throws ArgumentError solve(gp, ConfigsMin(2))
@test solve(gp, ConfigsMin(Single)) isa Array
@test_throws AssertionError ConfigsMin(0)
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 188 | using GenericTensorNetworks.SimpleMultiprocessing, Test
@testset "multiprocessing" begin
results = multiprocess_run(x->x^2, collect(1:5))
@test results == [1, 2, 3, 4, 5] .^ 2
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1045 | using GenericTensorNetworks
using Test, Documenter
@testset "mods.jl" begin
include(pkgdir(GenericTensorNetworks, "src", "Mods.jl", "test", "runtests.jl"))
end
@testset "bitvector" begin
include("bitvector.jl")
end
@testset "arithematics" begin
include("arithematics.jl")
end
@testset "independence polynomial" begin
include("graph_polynomials.jl")
end
@testset "configurations" begin
include("configurations.jl")
end
@testset "bounding" begin
include("bounding.jl")
end
@testset "interfaces" begin
include("interfaces.jl")
end
@testset "networks" begin
include("networks/networks.jl")
end
@testset "graphs" begin
include("graphs.jl")
end
@testset "visualize" begin
include("visualize.jl")
end
@testset "fileio" begin
include("fileio.jl")
end
@testset "multiprocessing" begin
include("multiprocessing.jl")
end
using CUDA
if CUDA.functional()
@testset "cuda" begin
include("cuda.jl")
end
end
# --------------
# doctests
# --------------
doctest(GenericTensorNetworks)
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1219 | using GenericTensorNetworks, Test, Graphs
using LuxorGraphPlot: StressLayout, SpringLayout, Luxor
@testset "visualize" begin
graph = smallgraph(:petersen)
@test show_graph(graph) isa Any
configs = [rand(Bool, 10) for i=1:5, j=1:3]
@test show_configs(graph, StressLayout(), configs) isa Luxor.Drawing
end
@testset "einsum" begin
graph = smallgraph(:petersen)
pb = GenericTensorNetwork(IndependentSet(graph))
@test show_einsum(pb.code; layout=SpringLayout(; optimal_distance=25), annotate_tensors=true) isa Luxor.Drawing
@test show_einsum(pb.code; layout=SpringLayout(; optimal_distance=25), locs=([(randn(), randn()) .* 40 for i=1:25], Dict(i=>(randn(), randn()) .* 40 for i=1:10))) isa Luxor.Drawing
end
@testset "landscape" begin
graph = smallgraph(:petersen)
pb = GenericTensorNetwork(IndependentSet(graph))
res = solve(pb, ConfigsMax(2))[]
@test show_landscape((x, y)->hamming_distance(x, y) <= 2, res; layout_method=:spring) isa Luxor.Drawing
@test show_landscape((x, y)->hamming_distance(x, y) <= 2, res; layout_method=:stress) isa Luxor.Drawing
@test show_landscape((x, y)->hamming_distance(x, y) <= 2, res; layout_method=:spectral) isa Luxor.Drawing
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2190 | using Test, GenericTensorNetworks, Graphs
@testset "enumerating - coloring" begin
g = SimpleGraph(5)
for (i,j) in [(1,2),(2,3),(3,4),(4,1),(1,5),(2,4)]
add_edge!(g, i, j)
end
code = GenericTensorNetwork(Coloring{3}(g); optimizer=GreedyMethod())
res = GenericTensorNetworks.best_solutions(code; all=true)[]
@test length(res.c.data) == 12
g = smallgraph(:petersen)
code = GenericTensorNetwork(Coloring{3}(g); optimizer=GreedyMethod())
res = GenericTensorNetworks.best_solutions(code; all=true)[]
@test length(res.c.data) == 120
c = solve(code, SingleConfigMax())[]
@test c.c.data ∈ res.c.data
@test is_vertex_coloring(g, c.c.data)
end
@testset "weighted coloring" begin
g = smallgraph(:petersen)
problem = GenericTensorNetwork(Coloring{3}(g, fill(2, 15)))
@test get_weights(problem) == fill(2, 15)
@test get_weights(chweights(problem, fill(3, 15))) == fill(3, 15)
@test solve(problem, SizeMax())[].n == 30
res = solve(problem, SingleConfigMax())[].c.data
@test is_vertex_coloring(g, res)
end
@testset "empty graph" begin
g = SimpleGraph(4)
pb = GenericTensorNetwork(Coloring{3}(g))
@test solve(pb, SizeMax()) !== 4
end
@testset "planar gadget checking" begin
function graph_crossing_gadget()
edges = [
(1,2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 1),
(9, 10), (10, 11), (11, 12), (12, 9),
(1, 9), (3, 10), (5, 11), (7, 12),
(2, 10), (4, 11), (6, 12), (8, 9),
(13, 9), (13, 10), (13, 11), (13, 12),
]
g = SimpleGraph(13)
for (i, j) in edges
add_edge!(g, i, j)
end
return g
end
g = graph_crossing_gadget()
problem = GenericTensorNetwork(Coloring{3}(g); openvertices=[3, 5])
res = solve(problem, ConfigsMax())
for i=1:3
for ci in res[i,i].c
@test ci[1] === ci[3] === ci[5] === ci[7] == i-1
end
end
for (i, j) in [(1, 2), (1, 3), (2, 3), (2,1), (3, 1), (3, 2)]
for ci in res[i,j].c
@test ci[1] === ci[5] == j-1
@test ci[3] === ci[7] == i-1
end
end
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1212 | using GenericTensorNetworks, Test, Graphs
@testset "dominating set basic" begin
g = smallgraph(:petersen)
mask = trues(10)
mask[neighbors(g, 1)] .= false
@test is_dominating_set(g, mask)
mask[1] = false
@test !is_dominating_set(g, mask)
@test GenericTensorNetworks.dominating_set_tensor(TropicalF64(0), TropicalF64(1), 3)[:,:,1] == TropicalF64[-Inf 0.0; 0 0]
@test GenericTensorNetworks.dominating_set_tensor(TropicalF64(0), TropicalF64(1), 3)[:,:,2] == TropicalF64[1.0 1.0; 1.0 1.0]
end
@testset "dominating set v.s. maximal IS" begin
g = smallgraph(:petersen)
gp1 = GenericTensorNetwork(DominatingSet(g))
@test get_weights(gp1) == UnitWeight()
@test get_weights(chweights(gp1, fill(3, 10))) == fill(3, 10)
@test solve(gp1, SizeMax())[].n == 10
res1 = solve(gp1, ConfigsMin())[].c
gp2 = GenericTensorNetwork(MaximalIS(g))
res2 = solve(gp2, ConfigsMin())[].c
@test res1 == res2
configs = solve(gp2, ConfigsAll())[]
for config in configs
@test is_dominating_set(g, config)
end
end
@testset "empty graph" begin
g = SimpleGraph(4)
pb = GenericTensorNetwork(DominatingSet(g))
@test solve(pb, SizeMax()) !== 4
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 794 | using GenericTensorNetworks, Test, Graphs
@testset "mis compactify" begin
g = SimpleGraph(6)
for (i,j) in [(1,2), (2,3), (4,5), (5,6), (1,6)]
add_edge!(g, i, j)
end
g = GenericTensorNetwork(IndependentSet(g); openvertices=[1,4,6,3])
m = solve(g, SizeMax())
@test m isa Array{Tropical{Float64}, 4}
@test count(!iszero, m) == 12
m1 = mis_compactify!(copy(m))
@test count(!iszero, m1) == 3
potential = zeros(Float64, 4)
m2 = mis_compactify!(copy(m); potential)
@test count(!iszero, m2) == 1
@test get_weights(g) == UnitWeight()
@test get_weights(chweights(g, fill(3, 6))) == fill(3, 6)
end
@testset "empty graph" begin
g = SimpleGraph(4)
pb = GenericTensorNetwork(IndependentSet(g))
@test solve(pb, SizeMax()) !== 4
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1501 | using Test, GenericTensorNetworks, Graphs
using GenericTensorNetworks: solutions
@testset "enumerating - matching" begin
g = smallgraph(:petersen)
code = GenericTensorNetwork(Matching(g); optimizer=GreedyMethod(), fixedvertices=Dict())
res = solutions(code, CountingTropicalF64; all=true)[]
@test res.n == 5
@test length(res.c.data) == 6
code = GenericTensorNetwork(Matching(g); optimizer=GreedyMethod(), fixedvertices=Dict((1,2)=>1))
@test get_weights(code) == UnitWeight()
@test get_weights(chweights(code, fill(3, 15))) == fill(3, 15)
res = solutions(code, CountingTropicalF64; all=true)[]
@test res.n == 5
k = findfirst(x->x==(1,2), labels(code))
@test length(res.c.data) == 2 && res.c.data[1][k] == 1 && res.c.data[2][k] == 1
end
@testset "match polynomial" begin
g = SimpleGraph(7)
for (i,j) in [(1,2),(2,3),(3,4),(4,5),(5,6),(6,1),(1,7)]
add_edge!(g, i, j)
end
@test graph_polynomial(GenericTensorNetwork(Matching(g)), Val(:polynomial))[] == Polynomial([1,7,13,5])
g = smallgraph(:petersen)
@test graph_polynomial(GenericTensorNetwork(Matching(g)), Val(:polynomial))[].coeffs == [6, 90, 145, 75, 15, 1][end:-1:1]
end
@testset "weighted matching" begin
g = smallgraph(:petersen)
problem = GenericTensorNetwork(Matching(g, fill(2, 15)))
@test solve(problem, SizeMax())[].n == 10
res = solve(problem, SingleConfigMax())[].c.data
@test is_matching(g, res)
@test count_ones(res) * 2 == 10
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2365 | using GenericTensorNetworks, Test, Graphs
using GenericTensorNetworks: max_size, graph_polynomial
@testset "graph utils" begin
g2 = SimpleGraph(3)
add_edge!(g2, 1,2)
for g in [smallgraph(:petersen), g2]
gp = GenericTensorNetwork(MaxCut(g))
mc = max_size(gp)
config = solve(gp, SingleConfigMax())[].c.data
@test cut_size(g, config) == mc
end
g = smallgraph(:petersen)
# weighted
ws = collect(1:ne(g))
gp = GenericTensorNetwork(MaxCut(g, ws))
@test get_weights(gp) == [ws..., zeros(10)...]
@test get_weights(chweights(gp, fill(3, 25))) == fill(3, 25)
mc = max_size(gp)
config = solve(gp, SingleConfigMax())[].c.data
@test solve(gp, CountingMax())[].c == 2
@test cut_size(g, config; edge_weights=ws) == mc
end
@testset "MaxCut" begin
g = SimpleGraph(5)
for (i,j) in [(1,2),(2,3),(3,4),(4,1),(1,5),(2,4)]
add_edge!(g, i, j)
end
@test graph_polynomial(GenericTensorNetwork(MaxCut(g)), Val(:polynomial))[] == Polynomial([2,2,4,12,10,2])
@test graph_polynomial(GenericTensorNetwork(MaxCut(g)), Val(:finitefield))[] == Polynomial([2,2,4,12,10,2])
end
@testset "enumerating - max cut" begin
g = SimpleGraph(5)
for (i,j) in [(1,2),(2,3),(3,4),(4,1),(1,5),(2,4)]
add_edge!(g, i, j)
end
code = GenericTensorNetwork(MaxCut(g); optimizer=GreedyMethod())
res = GenericTensorNetworks.best_solutions(code; all=true)[]
@test length(res.c.data) == 2
@test cut_size(g, res.c.data[1]) == 5
end
@testset "fix vertices - max cut" begin
g = SimpleGraph(5)
for (i,j) in [(1,2),(2,3),(3,4),(4,1),(1,5),(2,4)]
add_edge!(g, i, j)
end
fixedvertices = Dict(1=>1, 4=>0)
problem = GenericTensorNetwork(MaxCut(g), fixedvertices=fixedvertices)
optimal_config = solve(problem, ConfigsMax())[].c
@test length(optimal_config) == 1
@test optimal_config[1] == StaticBitVector(Array{Bool, 1}([1, 0, 1, 0, 0]))
end
@testset "vertex weights" begin
g = smallgraph(:petersen)
edge_weights = collect(1:ne(g))
vertex_weights = collect(1:nv(g))
gp = GenericTensorNetwork(MaxCut(g, edge_weights, vertex_weights))
mc = max_size(gp)
config = solve(gp, SingleConfigMax())[].c.data
@test solve(gp, CountingMax())[].c == 1
@test cut_size(g, config; edge_weights, vertex_weights) == mc
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2432 | using GenericTensorNetworks, Test, Graphs
using GenericTensorNetworks: graph_polynomial
@testset "counting maximal IS" begin
g = random_regular_graph(20, 3)
gp = GenericTensorNetwork(MaximalIS(g), optimizer=KaHyParBipartite(sc_target=20))
@test get_weights(gp) == UnitWeight()
@test get_weights(chweights(gp, fill(3, 20))) == fill(3, 20)
cs = graph_polynomial(gp, Val(:fft); r=1.0)[]
gp = GenericTensorNetwork(MaximalIS(g), optimizer=SABipartite(sc_target=20))
cs2 = graph_polynomial(gp, Val(:polynomial))[]
gp = GenericTensorNetwork(MaximalIS(g), optimizer=GreedyMethod())
cs3 = graph_polynomial(gp, Val(:finitefield))[]
cg = complement(g)
cliques = maximal_cliques(cg)
for i=1:20
c = count(x->length(x)==i, cliques)
if c > 0
@test cs2.coeffs[i+1] == c
@test cs3.coeffs[i+1] == c
@test cs.coeffs[i+1] ≈ c
end
end
end
@testset "counting minimum maximal IS" begin
g = smallgraph(:tutte)
net = GenericTensorNetwork(MaximalIS(g))
res = solve(net, SizeMin())[]
res2 = solve(net, SizeMin(10))[]
res3 = solve(net, SingleConfigMin(10))[]
poly = solve(net, GraphPolynomial())[]
@test poly == Polynomial([fill(0.0, 13)..., 2, 150, 7510, 71669, 66252, 14925, 571])
@test res.n == 13
@test res2.orders == Tropical.([13, 13, fill(14, 8)...])
@test all(r->is_maximal_independent_set(g, r[2].c.data) && count_ones(r[2].c.data)==r[1].n, zip(res2.orders, res3.orders))
@test solve(net, CountingMin())[].c == 2
min2 = solve(net, CountingMin(3))[]
@test min2.maxorder == 15
@test min2.coeffs == (2, 150, 7510)
for bounded in [false, true]
@info("bounded = ", bounded, ", configs max1")
@test length(solve(net, ConfigsMin(; bounded=bounded))[].c) == 2
println("bounded = ", bounded, ", configs max3")
cmin2 = solve(net, ConfigsMin(3; bounded=bounded))[]
@test cmin2.maxorder == 15
@test length.(cmin2.coeffs) == (2, 150, 7510)
println("bounded = ", bounded, ", single config min")
c = solve(net, SingleConfigMin(; bounded=bounded), T=Int64)[].c.data
@test c ∈ cmin2.coeffs[1].data
@test is_maximal_independent_set(g, c)
@test count(!iszero, c) == 13
end
end
@testset "empty graph" begin
g = SimpleGraph(4)
@test solve(GenericTensorNetwork(MaximalIS(g)), SizeMax()) !== 4
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 780 | using GenericTensorNetworks, Test, Graphs
@testset "open pit mining" begin
rewards = zeros(Int,6,6)
rewards[1,:] .= [-4,-7,-7,-17,-7,-26]
rewards[2,2:end-1] .= [39, -7, -7, -4]
rewards[3,3:end-2] .= [1, 8]
problem = GenericTensorNetwork(OpenPitMining(rewards))
@test get_weights(problem) == [-4,-7,-7,-17,-7,-26, 39, -7, -7, -4, 1, 8]
@test get_weights(chweights(problem, fill(3, 20))) == fill(3, 12)
res = solve(problem, SingleConfigMax())[]
@test is_valid_mining(rewards, res.c.data)
@test res.n == 21
print_mining(rewards, res.c.data)
val, mask = GenericTensorNetworks.open_pit_mining_branching(rewards)
@test val == res.n
res_b = map(block->mask[block...], problem.problem.blocks)
@test res_b == [res.c.data...]
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 530 | using GenericTensorNetworks, Test
@testset "paint shop" begin
syms = collect("abaccb")
pb = GenericTensorNetwork(PaintShop(syms))
@test get_weights(pb) == UnitWeight()
@test get_weights(chweights(pb, fill(3, 15))) == UnitWeight()
@test solve(pb, SizeMin())[] == Tropical(2.0)
config = solve(pb, SingleConfigMin())[].c.data
coloring = paint_shop_coloring_from_config(pb.problem, config)
@test num_paint_shop_color_switch(syms, coloring) == 2
@test bv"100" ∈ solve(pb, ConfigsMin())[].c.data
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2227 | using Test
using GenericTensorNetworks
@testset "CNF" begin
@bools x y z a b c
println(x)
@test x == BoolVar(:x, false)
@test ¬x == BoolVar(:x, true)
@test x ∨ ¬y ∨ (z ∨ (¬a ∨ b)) == CNFClause([x, ¬y, z, ¬a, b])
c1 = x ∨ ¬y
c2 = c ∨ (¬a ∨ b)
c3 = (z ∨ ¬a) ∨ y
c4 = (c ∨ z) ∨ ¬b
println(c4)
@test c1 ∧ c2 == CNF([c1, c2])
@test (c1 ∧ c2) ∧ c3 == CNF([c1, c2, c3])
@test c1 ∧ (c2 ∧ c3) == CNF([c1, c2, c3])
@test (c1 ∧ c4) ∧ (c2 ∧ c3) == CNF([c1, c4, c2, c3])
cnf = (c1 ∧ c4) ∧ (c2 ∧ c3)
println(cnf)
gp = GenericTensorNetwork(Satisfiability(cnf))
@test satisfiable(cnf, Dict(:x=>true, :y=>true, :z=>true, :a=>false, :b=>false, :c=>true))
@test !satisfiable(cnf, Dict(:x=>false, :y=>true, :z=>true, :a=>false, :b=>false, :c=>true))
@test get_weights(gp) == UnitWeight()
@test get_weights(chweights(gp, fill(3, 4))) == fill(3,4)
@test_throws AssertionError Satisfiability(cnf, fill(3, 9))
end
@testset "enumeration - sat" begin
@bools x y z a b c
c1 = x ∨ ¬y
c2 = c ∨ (¬a ∨ b)
c3 = (z ∨ ¬a) ∨ y
c4 = (c ∨ z) ∨ ¬b
cnf = (c1 ∧ c4) ∧ (c2 ∧ c3)
gp = GenericTensorNetwork(Satisfiability(cnf))
@test solve(gp, SizeMax())[].n == 4.0
res = GenericTensorNetworks.best_solutions(gp; all=true)[].c.data
for i=0:1<<6-1
v = StaticBitVector(Bool[i>>(k-1) & 1 for k=1:6])
if v ∈ res
@test satisfiable(gp.problem.cnf, Dict(zip(labels(gp), v)))
else
@test !satisfiable(gp.problem.cnf, Dict(zip(labels(gp), v)))
end
end
end
@testset "weighted cnf" begin
@bools x y z a b c
c1 = x ∨ ¬y
c2 = c ∨ (¬a ∨ b)
c3 = (z ∨ ¬a) ∨ y
c4 = (c ∨ z) ∨ ¬b
cnf = (c1 ∧ c4) ∧ (c2 ∧ c3)
gp = GenericTensorNetwork(Satisfiability(cnf, fill(2, length(cnf))))
@test solve(gp, SizeMax())[].n == 8.0
res = GenericTensorNetworks.best_solutions(gp; all=true)[].c.data
for i=0:1<<6-1
v = StaticBitVector(Bool[i>>(k-1) & 1 for k=1:6])
if v ∈ res
@test satisfiable(gp.problem.cnf, Dict(zip(labels(gp), v)))
else
@test !satisfiable(gp.problem.cnf, Dict(zip(labels(gp), v)))
end
end
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 543 | using GenericTensorNetworks, Test, Graphs
@testset "set covering" begin
sets = [[1, 2, 5], [1, 3], [2, 4], [3, 6], [2, 3, 6]] # each set is a vertex
gp = GenericTensorNetwork(SetCovering(sets); optimizer=GreedyMethod())
@test get_weights(gp) == UnitWeight()
@test get_weights(chweights(gp, fill(3, 5))) == fill(3,5)
res = solve(gp, ConfigsMin())[]
@test res.n == 3
@test BitVector(Bool[1,0,1,1,0]) ∈ res.c.data
@test BitVector(Bool[1,0,1,0,1]) ∈ res.c.data
@test all(x->is_set_covering(sets, x),res.c)
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 617 | using GenericTensorNetworks, Test, Graphs
@testset "set packing" begin
sets = [[1, 2, 5], [1, 3], [2, 4], [3, 6], [2, 3, 6]] # each set is a vertex
gp = GenericTensorNetwork(SetPacking(sets); optimizer=GreedyMethod())
@test get_weights(gp) == UnitWeight()
@test get_weights(chweights(gp, fill(3, 5))) == fill(3,5)
res = GenericTensorNetworks.best_solutions(gp; all=true)[]
@test res.n == 2
@test BitVector(Bool[0,0,1,1,0]) ∈ res.c.data
@test BitVector(Bool[1,0,0,1,0]) ∈ res.c.data
@test BitVector(Bool[0,1,1,0,0]) ∈ res.c.data
@test all(x->is_set_packing(sets, x),res.c)
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 4568 | using GenericTensorNetworks, Test, Graphs
@testset "memory estimation" begin
g = smallgraph(:petersen)
ecliques = [[e.src, e.dst] for e in edges(g)]
cliques = [ecliques..., [[v] for v in vertices(g)]...]
J = rand(15)
h = randn(10) .* 0.5
weights = [J..., h...]
gp = GenericTensorNetwork(SpinGlass(10, cliques, weights))
cfg(x) = [(x>>i & 1) for i=0:9]
energies = [spinglass_energy(cliques, cfg(b); weights) for b=0:1<<nv(g)-1]
energies2 = [spinglass_energy(g, cfg(b); J, h) for b=0:1<<nv(g)-1]
@test energies ≈ energies2
sorted_energies = sort(energies)
@test solve(gp, SizeMax())[].n ≈ sorted_energies[end]
@test solve(gp, SizeMin())[].n ≈ sorted_energies[1]
@test getfield.(solve(gp, SizeMax(2))[].orders |> collect, :n) ≈ sorted_energies[end-1:end]
res = solve(gp, SingleConfigMax(2))[].orders |> collect
@test getfield.(res, :n) ≈ sorted_energies[end-1:end]
@test spinglass_energy(cliques, res[1].c.data; weights) ≈ res[end-1].n
@test spinglass_energy(cliques, res[2].c.data; weights) ≈ res[end].n
val, ind = findmax(energies)
# integer weights
weights = UnitWeight()
gp = GenericTensorNetwork(SpinGlass(10, ecliques, weights))
energies = [spinglass_energy(ecliques, cfg(b); weights) for b=0:1<<nv(g)-1]
sorted_energies = sort(energies)
@test solve(gp, CountingMax(2))[].maxorder ≈ sorted_energies[end]
@test solve(gp, CountingMin())[].n ≈ sorted_energies[1]
@test solve(gp, ConfigsMax(2))[].maxorder ≈ sorted_energies[end]
@test solve(gp, ConfigsMin())[].n ≈ sorted_energies[1]
@test solve(gp, CountingAll())[] ≈ 1024
poly = solve(gp, GraphPolynomial(; method=:laurent))[]
@test poly.order[] == sorted_energies[1]
@test poly.order[] + length(poly.coeffs) - 1 == sorted_energies[end]
end
@testset "auto laurent" begin
hyperDim = 2
blockDim = 3
graph = [[2, 12], [3, 11], [1, 5], [2, 4], [4, 5], [4, 8], [5, 7], [1, 9], [3, 7], [5, 9], [6, 8], [4, 9], [6, 7], [7, 12], [9, 10], [10, 12], [4, 6], [5, 6], [10, 11], [1, 2, 12], [1, 3, 11], [1, 11, 12], [2, 3, 10], [2, 10, 12], [3, 10, 11], [4, 8, 12], [4, 9, 11], [5, 7, 12], [7, 8, 12], [6, 7, 11], [7, 9, 11], [7, 11, 12], [5, 9, 10], [6, 8, 10], [8, 9, 10], [8, 10, 12], [9, 10, 11], [1, 2, 9], [1, 3, 8], [1, 8, 9], [2, 3, 7], [2, 7, 9], [3, 7, 8], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
num_vertices = blockDim* 2^hyperDim
weights = ones(Int, length(graph));
problem = GenericTensorNetwork(SpinGlass(num_vertices, graph, weights));
poly = solve(problem, GraphPolynomial())[]
@test poly isa LaurentPolynomial
weights = ones(length(graph));
problem = GenericTensorNetwork(SpinGlass(num_vertices, graph, weights))
poly = solve(problem, GraphPolynomial())[]
@test poly isa LaurentPolynomial
end
@testset "memory estimation" begin
g = smallgraph(:petersen)
J = rand(15)
h = randn(10) .* 0.5
gp = GenericTensorNetwork(SpinGlass(g, J, h))
@test contraction_complexity(gp).sc <= 5
M = zeros(10, 10)
for (e,j) in zip(edges(g), J)
M[e.src, e.dst] = j
end; M += M'
gp2 = GenericTensorNetwork(spin_glass_from_matrix(M, h))
@test gp2.problem.weights ≈ gp.problem.weights
cfg(x) = [(x>>i & 1) for i=0:9]
energies = [spinglass_energy(g, cfg(b); J=J, h) for b=0:1<<nv(g)-1]
sorted_energies = sort(energies)
@test solve(gp, SizeMax())[].n ≈ sorted_energies[end]
@test solve(gp, SizeMin())[].n ≈ sorted_energies[1]
@test getfield.(solve(gp, SizeMax(2))[].orders |> collect, :n) ≈ sorted_energies[end-1:end]
res = solve(gp, SingleConfigMax(2))[].orders |> collect
@test getfield.(res, :n) ≈ sorted_energies[end-1:end]
@test spinglass_energy(g, res[1].c.data; J, h) ≈ res[end-1].n
@test spinglass_energy(g, res[2].c.data; J, h) ≈ res[end].n
val, ind = findmax(energies)
# integer weights
J = UnitWeight()
h = ZeroWeight()
gp = GenericTensorNetwork(SpinGlass(g, J, h))
energies = [spinglass_energy(g, cfg(b); J=J, h) for b=0:1<<nv(g)-1]
sorted_energies = sort(energies)
@test solve(gp, CountingMax(2))[].maxorder ≈ sorted_energies[end]
@test solve(gp, CountingMin())[].n ≈ sorted_energies[1]
@test solve(gp, ConfigsMax(2))[].maxorder ≈ sorted_energies[end]
@test solve(gp, ConfigsMin())[].n ≈ sorted_energies[1]
@test solve(gp, CountingAll())[] ≈ 1024
poly = solve(gp, GraphPolynomial())[]
@test poly.order[] == sorted_energies[1]
@test poly.order[] + length(poly.coeffs) - 1 == sorted_energies[end]
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 754 | using GenericTensorNetworks: select_dims
using Test
@testset "select dims" begin
a, b, c = randn(2), randn(2, 2), randn(2,2,2)
a_, b_, c_ = select_dims([a, b, c], [[1], [1,2], [1,2,3]], Dict(1=>1, 3=>0))
@test a_ == a[2:2]
@test b_ == b[2:2, :]
@test c_ == c[2:2, :, 1:1]
a, b = randn(3), randn(3,3,3)
a_, b_ = select_dims([a, b], [[1], [2,3,1]], Dict(1=>1, 3=>2))
@test a_ == a[2:2]
@test b_ == b[:,3:3,2:2]
end
include("IndependentSet.jl")
include("MaximalIS.jl")
include("MaxCut.jl")
include("SpinGlass.jl")
include("PaintShop.jl")
include("Coloring.jl")
include("Matching.jl")
include("Satisfiability.jl")
include("DominatingSet.jl")
include("SetPacking.jl")
include("SetCovering.jl")
include("OpenPitMining.jl") | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 4445 | # GenericTensorNetworks
[](https://github.com/QuEraComputing/GenericTensorNetworks.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/QuEraComputing/GenericTensorNetworks.jl)
[](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/)
This package implements generic tensor networks to compute *solution space properties* of a class of hard combinatorial optimization problems.
The *solution space properties* include
* The maximum/minimum solution sizes,
* The number of solutions at certain sizes,
* The enumeration/sampling of solutions at certain sizes.
The types of problems that can be solved using this package include [Independent set problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/IndependentSet/), [Maximal independent set problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/MaximalIS/), [Spin-glass problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/SpinGlass/), [Cutting problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/MaxCut/), [Vertex matching problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/Matching/), [Binary paint shop problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/PaintShop/), [Coloring problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/Coloring/), [Dominating set problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/DominatingSet/), [Set packing problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/SetPacking/), [Satisfiability problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/Satisfiability/) and [Set covering problem](https://queracomputing.github.io/GenericTensorNetworks.jl/dev/generated/SetCovering/).
## Installation
<p>
GenericTensorNetworks is a
<a href="https://julialang.org">
<img src="https://raw.githubusercontent.com/JuliaLang/julia-logo-graphics/master/images/julia.ico" width="16em">
Julia Language
</a>
package. To install GenericTensorNetworks,
please <a href="https://docs.julialang.org/en/v1/manual/getting-started/">open
Julia's interactive session (known as REPL)</a> and press the <kbd>]</kbd> key in the REPL to use the package mode, and then type:
</p>
```julia
pkg> add GenericTensorNetworks
```
To update, just type `up` in the package mode.
We recommend that you use **Julia version >= 1.7**; otherwise, your program may suffer from significant (exponential in the tensor dimension) overheads when permuting the dimensions of a large tensor.
If you have to use an older version of Julia, you can overwrite the `LinearAlgebra.permutedims!` by adding the following patch to your own project.
```julia
# only required when your Julia version is < 1.7
using TensorOperations, LinearAlgebra
function LinearAlgebra.permutedims!(C::Array{T,N}, A::StridedArray{T,N}, perm) where {T,N}
if isbitstype(T)
TensorOperations.tensorcopy!(A, ntuple(identity,N), C, perm)
else
invoke(permutedims!, Tuple{Any,AbstractArray,Any}, C, A, perm)
end
end
```
## Supporting and Citing
Much of the software in this ecosystem was developed as a part of an academic research project.
If you would like to help support it, please star the repository.
If you use our software as part of your research, teaching, or other activities, we would like to request you to cite our [work](https://arxiv.org/abs/2205.03718).
The
[CITATION.bib](https://github.com/QuEraComputing/GenericTensorNetworks.jl/blob/master/CITATION.bib) file in the root of this repository lists the relevant papers.
## Questions and Contributions
You can
* Post a question on [Julia Discourse forum](https://discourse.julialang.org/) and ping the package maintainer with `@1115`.
* Discuss in the `#graphs` channel of the [Julia Slack](https://julialang.org/community/) and ping the package maintainer with `@JinGuo Liu`.
* Open an [issue](https://github.com/QuEraComputing/GenericTensorNetworks.jl/issues) if you encounter any problems, or have any feature request.
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 6597 | # Gist of implementation
The code we will show below is a gist of how this package is implemented for pedagogical purpose, which covers many functionalities of the main repo without caring much about performance.
This project depends on multiple open source packages in the Julia ecosystem:
* [OMEinsum](https://github.com/under-Peter/OMEinsum.jl) and [OMEinsumContractionOrders](https://github.com/TensorBFS/OMEinsumContractionOrders.jl) are packages providing the support for Einstein's (or tensor network) notation and state-of-the-art algorithms for contraction order optimization, which includes multiple state of the art algorithms.
* [TropicalNumbers](https://github.com/TensorBFS/TropicalNumbers.jl) and [TropicalGEMM](https://github.com/TensorBFS/TropicalGEMM.jl) are packages providing tropical number and efficient tropical matrix multiplication.
* [Graphs](https://github.com/JuliaGraphs/Graphs.jl) is a foundational package for graph manipulation in the Julia community.
* [Polynomials](https://github.com/JuliaMath/Polynomials.jl) is a package providing polynomial algebra and polynomial fitting.
* [Mods](https://github.com/scheinerman/Mods.jl) and the [Primes](https://github.com/JuliaMath/Primes.jl) package providing finite field algebra and prime number manipulation.
They can be installed in a similar way to `GenericTensorNetworks`.
After installing the required packages, one can open a Julia REPL, and copy-paste the following code snippet into it.
```julia
using OMEinsum
using Graphs
using Random
# generate a random regular graph of size 50, degree 3
graph = (Random.seed!(2); Graphs.random_regular_graph(50, 3))
# generate einsum code, i.e. the labels of tensors
code = EinCode(([minmax(e.src,e.dst) for e in Graphs.edges(graph)]..., # labels for edge tensors
[(i,) for i in Graphs.vertices(graph)]...), ()) # labels for vertex tensors
# an einsum contraction without a contraction order specified is called `EinCode`,
# an einsum contraction having a contraction order (specified as a tree structure) is called `NestedEinsum`.
# assign each label a dimension-2, it will be used in the contraction order optimization
# `uniquelabels` function extracts the tensor labels into a vector.
size_dict = Dict([s=>2 for s in uniquelabels(code)])
# optimize the contraction order using the `TreeSA` method; the target space complexity is 2^17
optimized_code = optimize_code(code, size_dict, TreeSA())
println("time/space complexity is $(OMEinsum.timespace_complexity(optimized_code, size_dict))")
# a function for computing the independence polynomial
function independence_polynomial(x::T, code) where {T}
xs = map(getixsv(code)) do ix
# if the tensor rank is 1, create a vertex tensor.
# otherwise the tensor rank must be 2, create a bond tensor.
length(ix)==1 ? [one(T), x] : [one(T) one(T); one(T) zero(T)]
end
# both `EinCode` and `NestedEinsum` are callable, inputs are tensors.
code(xs...)
end
########## COMPUTING THE MAXIMUM INDEPENDENT SET SIZE AND ITS COUNTING/DEGENERACY ###########
# using Tropical numbers to compute the MIS size and the MIS degeneracy.
using TropicalNumbers
mis_size(code) = independence_polynomial(TropicalF64(1.0), code)[]
println("the maximum independent set size is $(mis_size(optimized_code).n)")
# A `CountingTropical` object has two fields, tropical field `n` and counting field `c`.
mis_count(code) = independence_polynomial(CountingTropical{Float64,Float64}(1.0, 1.0), code)[]
println("the degeneracy of maximum independent sets is $(mis_count(optimized_code).c)")
########## COMPUTING THE INDEPENDENCE POLYNOMIAL ###########
# using Polynomial numbers to compute the polynomial directly
using Polynomials
println("the independence polynomial is $(independence_polynomial(Polynomial([0.0, 1.0]), optimized_code)[])")
########## FINDING MIS CONFIGURATIONS ###########
# define the set algebra
struct ConfigEnumerator{N}
# NOTE: BitVector is dynamic and it can be very slow; check our repo for the static version
data::Vector{BitVector}
end
function Base.:+(x::ConfigEnumerator{N}, y::ConfigEnumerator{N}) where {N}
res = ConfigEnumerator{N}(vcat(x.data, y.data))
return res
end
function Base.:*(x::ConfigEnumerator{L}, y::ConfigEnumerator{L}) where {L}
M, N = length(x.data), length(y.data)
z = Vector{BitVector}(undef, M*N)
for j=1:N, i=1:M
z[(j-1)*M+i] = x.data[i] .| y.data[j]
end
return ConfigEnumerator{L}(z)
end
Base.zero(::Type{ConfigEnumerator{N}}) where {N} = ConfigEnumerator{N}(BitVector[])
Base.one(::Type{ConfigEnumerator{N}}) where {N} = ConfigEnumerator{N}([falses(N)])
# the algebra sampling one of the configurations
struct ConfigSampler{N}
data::BitVector
end
function Base.:+(x::ConfigSampler{N}, y::ConfigSampler{N}) where {N} # biased sampling: return `x`
return x # randomly pick one
end
function Base.:*(x::ConfigSampler{L}, y::ConfigSampler{L}) where {L}
ConfigSampler{L}(x.data .| y.data)
end
Base.zero(::Type{ConfigSampler{N}}) where {N} = ConfigSampler{N}(trues(N))
Base.one(::Type{ConfigSampler{N}}) where {N} = ConfigSampler{N}(falses(N))
# enumerate all configurations if `all` is true; compute one otherwise.
# a configuration is stored in the data type of `StaticBitVector`; it uses integers to represent bit strings.
# `ConfigTropical` is defined in `TropicalNumbers`. It has two fields: tropical number `n` and optimal configuration `config`.
# `CountingTropical{T,<:ConfigEnumerator}` stores configurations instead of simple counting.
function mis_config(code; all=false)
# map a vertex label to an integer
vertex_index = Dict([s=>i for (i, s) in enumerate(uniquelabels(code))])
N = length(vertex_index) # number of vertices
xs = map(getixsv(code)) do ix
T = all ? CountingTropical{Float64, ConfigEnumerator{N}} : CountingTropical{Float64, ConfigSampler{N}}
if length(ix) == 2
return [one(T) one(T); one(T) zero(T)]
else
s = falses(N)
s[vertex_index[ix[1]]] = true # one hot vector
if all
[one(T), T(1.0, ConfigEnumerator{N}([s]))]
else
[one(T), T(1.0, ConfigSampler{N}(s))]
end
end
end
return code(xs...)
end
println("one of the optimal configurations is $(mis_config(optimized_code; all=false)[].c.data)")
# direct enumeration of configurations can be very slow; please check the bounding version in our Github repo.
println("all optimal configurations are $(mis_config(optimized_code; all=true)[].c)")
```
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 3863 | ```@meta
CurrentModule = GenericTensorNetworks
```
# GenericTensorNetworks
This package implements generic tensor networks to compute *solution space properties* of a class of hard combinatorial problems.
The *solution space properties* include
* The maximum/minimum solution sizes,
* The number of solutions at certain sizes,
* The enumeration of solutions at certain sizes.
* The direct sampling of solutions at certain sizes.
The solvable problems include [Independent set problem](@ref), [Maximal independent set problem](@ref), [Spin-glass problem](@ref), [Cutting problem](@ref), [Vertex matching problem](@ref), [Binary paint shop problem](@ref), [Coloring problem](@ref), [Dominating set problem](@ref), [Satisfiability problem](@ref), [Set packing problem](@ref) and [Set covering problem](@ref).
## Background knowledge
Please check our paper ["Computing properties of independent sets by generic programming tensor networks"](https://arxiv.org/abs/2205.03718).
If you find our paper or software useful in your work, we would be grateful if you could cite our work. The [CITATION.bib](https://github.com/QuEraComputing/GenericTensorNetworks.jl/blob/master/CITATION.bib) file in the root of this repository lists the relevant papers.
## Quick start
You can find a set up guide in our [README](https://github.com/QuEraComputing/GenericTensorNetworks.jl).
To get started, open a Julia REPL and type the following code.
```@repl
using GenericTensorNetworks, Graphs#, CUDA
solve(
GenericTensorNetwork(IndependentSet(
Graphs.random_regular_graph(20, 3),
UnitWeight()); # default: uniform weight 1
optimizer = TreeSA(),
openvertices = (), # default: no open vertices
fixedvertices = Dict() # default: no fixed vertices
),
GraphPolynomial();
usecuda=false # the default value
)
```
Here the main function [`solve`](@ref) takes three input arguments, the problem instance of type [`IndependentSet`](@ref), the property instance of type [`GraphPolynomial`](@ref) and an optional key word argument `usecuda` to decide use GPU or not.
If one wants to use GPU to accelerate the computation, the `, CUDA` should be uncommented.
An [`IndependentSet`](@ref) instance takes two positional arguments to initialize, the graph instance that one wants to solve and the weights for each vertex. Here, we use a random regular graph with 20 vertices and degree 3, and the default uniform weight 1.
The [`GenericTensorNetwork`](@ref) function is a constructor for the problem instance, which takes the problem instance as the first argument and optional key word arguments. The key word argument `optimizer` is for specifying the tensor network optimization algorithm.
The keyword argument `openvertices` is a tuple of labels for specifying the degrees of freedom not summed over, and `fixedvertices` is a label-value dictionary for specifying the fixed values of the degree of freedoms.
Here, we use [`TreeSA`](@ref) method as the tensor network optimizer, and leave `openvertices` the default values.
The [`TreeSA`](@ref) method finds the best contraction order in most of our applications, while the default [`GreedyMethod`](@ref) runs the fastest.
The first execution of this function will be a bit slow due to Julia's just in time compiling.
The subsequent runs will be fast.
The following diagram lists possible combinations of input arguments, where functions in the `Graph` are mainly defined in the package [Graphs](https://github.com/JuliaGraphs/Graphs.jl), and the rest can be found in this package.
```@raw html
<div align=center>
<img src="assets/fig7.svg" width="75%"/>
</div>
```⠀
You can find many examples in this documentation, a good one to start with is [Independent set problem](@ref).
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 13303 | # Performance Tips
## Optimize contraction orders
Let us use the independent set problem on 3-regular graphs as an example.
```@repl performancetips
using GenericTensorNetworks, Graphs, Random
graph = random_regular_graph(120, 3)
iset = IndependentSet(graph)
problem = GenericTensorNetwork(iset; optimizer=TreeSA(
sc_target=20, sc_weight=1.0, rw_weight=3.0, ntrials=10, βs=0.01:0.1:15.0, niters=20));
```
The [`GenericTensorNetwork`](@ref) constructor maps an independent set problem to a tensor network with optimized contraction order.
The key word argument `optimizer` specifies the contraction order optimizer of the tensor network.
Here, we choose the local search based [`TreeSA`](@ref) algorithm, which often finds the smallest time/space complexity and supports slicing.
One can type `?TreeSA` in a Julia REPL for more information about how to configure the hyper-parameters of the [`TreeSA`](@ref) method,
while the detailed algorithm explanation is in [arXiv: 2108.05665](https://arxiv.org/abs/2108.05665).
Alternative tensor network contraction order optimizers include
* [`GreedyMethod`](@ref) (default, fastest in searching speed but worst in contraction complexity)
* [`KaHyParBipartite`](@ref)
* [`SABipartite`](@ref)
For example, the `MergeGreedy()` here "contracts" tensors greedily whenever the contraction result has a smaller space complexity.
It can remove all vertex tensors (vectors) before entering the contraction order optimization algorithm.
The returned object `problem` contains a field `code` that specifies the tensor network with optimized contraction order.
For an independent set problem, the optimal contraction time/space complexity is ``\sim 2^{{\rm tw}(G)}``, where ``{\rm tw(G)}`` is the [tree-width](https://en.wikipedia.org/wiki/Treewidth) of ``G``.
One can check the time, space and read-write complexity with the [`contraction_complexity`](@ref) function.
```@repl performancetips
contraction_complexity(problem)
```
The return values are `log2` values of the number of multiplications, the number elements in the largest tensor during contraction and the number of read-write operations to tensor elements.
In this example, the number `*` operations is ``\sim 2^{21.9}``, the number of read-write operations are ``\sim 2^{20}``, and the largest tensor size is ``2^{17}``.
One can check the element size by typing
```@repl performancetips
sizeof(TropicalF64)
sizeof(TropicalF32)
sizeof(StaticBitVector{200,4})
sizeof(TruncatedPoly{5,Float64,Float64})
```
One can use [`estimate_memory`](@ref) to get a good estimation of peak memory in bytes.
For example, to compute the graph polynomial, the peak memory can be estimated as follows.
```@repl performancetips
estimate_memory(problem, GraphPolynomial(; method=:finitefield))
estimate_memory(problem, GraphPolynomial(; method=:polynomial))
```
The finite field approach only requires 298 KB memory, while using the [`Polynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomial-2) number type requires 71 MB memory.
!!! note
* The actual run time memory can be several times larger than the size of the maximum tensor, so the [`estimate_memory`](@ref) is more accurate in estimating the peak memory.
* For mutable element types like [`ConfigEnumerator`](@ref), none of memory estimation functions measure the actual memory usage correctly.
## Slicing technique
For large scale applications, it is also possible to slice over certain degrees of freedom to reduce the space complexity, i.e.
loop and accumulate over certain degrees of freedom so that one can have a smaller tensor network inside the loop due to the removal of these degrees of freedom.
In the [`TreeSA`](@ref) optimizer, one can set `nslices` to a value larger than zero to turn on this feature.
```@repl performancetips
problem = GenericTensorNetwork(iset; optimizer=TreeSA(βs=0.01:0.1:25.0, ntrials=10, niters=10));
contraction_complexity(problem)
problem = GenericTensorNetwork(iset; optimizer=TreeSA(βs=0.01:0.1:25.0, ntrials=10, niters=10, nslices=5));
contraction_complexity(problem)
```
In the second `IndependentSet` constructor, we slice over 5 degrees of freedom, which can reduce the space complexity by at most 5.
In this application, the slicing achieves the largest possible space complexity reduction 5, while the time and read-write complexity are only increased by less than 1,
i.e. the peak memory usage is reduced by a factor ``32``, while the (theoretical) computing time is increased by at a factor ``< 2``.
## GEMM for Tropical numbers
One can speed up the Tropical number matrix multiplication when computing the solution space property [`SizeMax`](@ref)`()` by using the Tropical GEMM routines implemented in package [`TropicalGEMM`](https://github.com/TensorBFS/TropicalGEMM.jl/).
```julia-repl
julia> using BenchmarkTools
julia> @btime solve(problem, SizeMax())
91.630 ms (19203 allocations: 23.72 MiB)
0-dimensional Array{TropicalF64, 0}:
53.0ₜ
julia> using TropicalGEMM
julia> @btime solve(problem, SizeMax())
8.960 ms (18532 allocations: 17.01 MiB)
0-dimensional Array{TropicalF64, 0}:
53.0ₜ
```
The `TropicalGEMM` package pirates the `LinearAlgebra.mul!` interface, hence it takes effect upon using.
The above example shows more than 10x speed up on a single thread CPU, which can be even faster if [the Julia multi-threading](https://docs.julialang.org/en/v1/manual/multi-threading/) if turned on.
The benchmark in the `TropicalGEMM` repo shows this performance is close to the theoretical optimal value.
## Multiprocessing
Submodule `GenericTensorNetworks.SimpleMutiprocessing` provides one function [`GenericTensorNetworks.SimpleMultiprocessing.multiprocess_run`](@ref) function for simple multi-processing jobs.
It is not directly related to `GenericTensorNetworks`, but is very convenient to have one.
Suppose we want to find the independence polynomial for multiple graphs with 4 processes.
We can create a file, e.g. named `run.jl` with the following content
```julia
using Distributed, GenericTensorNetworks.SimpleMultiprocessing
using Random, GenericTensorNetworks # to avoid multi-precompilation
@everywhere using Random, GenericTensorNetworks
results = multiprocess_run(collect(1:10)) do seed
Random.seed!(seed)
n = 10
@info "Graph size $n x $n, seed= $seed"
g = random_diagonal_coupled_graph(n, n, 0.8)
gp = GenericTensorNetwork(IndependentSet(g); optimizer=TreeSA())
res = solve(gp, GraphPolynomial())[]
return res
end
println(results)
```
One can run this script file with the following command
```bash
$ julia -p4 run.jl
From worker 3: [ Info: running argument 4 on device 3
From worker 4: [ Info: running argument 2 on device 4
From worker 5: [ Info: running argument 3 on device 5
From worker 2: [ Info: running argument 1 on device 2
From worker 3: [ Info: Graph size 10 x 10, seed= 4
From worker 4: [ Info: Graph size 10 x 10, seed= 2
From worker 5: [ Info: Graph size 10 x 10, seed= 3
From worker 2: [ Info: Graph size 10 x 10, seed= 1
From worker 4: [ Info: running argument 5 on device
...
```
You will see a vector of polynomials printed out.
## Make use of GPUs
To upload the computation to GPU, you just add `using CUDA` before calling the `solve` function, and set the keyword argument `usecuda` to `true`.
```julia-repl
julia> using CUDA
[ Info: OMEinsum loaded the CUDA module successfully
julia> solve(problem, SizeMax(), usecuda=true)
0-dimensional CuArray{TropicalF64, 0, CUDA.Mem.DeviceBuffer}:
53.0ₜ
```
Solution space properties computable on GPU includes
* [`SizeMax`](@ref) and [`SizeMin`](@ref)
* [`CountingAll`](@ref)
* [`CountingMax`](@ref) and [`CountingMin`](@ref)
* [`GraphPolynomial`](@ref)
* [`SingleConfigMax`](@ref) and [`SingleConfigMin`](@ref)
## Benchmarks
We run a single thread benchmark on central processing units (CPU) Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz, and its CUDA version on a GPU Tesla V100-SXM2 16G. The results are summarized in the following plot. The benchmark code can be found in [our paper repository](https://github.com/GiggleLiu/NoteOnTropicalMIS/tree/master/benchmarks).

This benchmark results is for computing different solution space properties of independent sets of random three-regular graphs with different tensor element types. The time in these plots only includes tensor network contraction, without taking into account the contraction order finding and just-in-time compilation time. Legends are properties, algebra, and devices that we used in the computation; one can find the corresponding computed solution space property in Table 1 in the [paper](https://arxiv.org/abs/2205.03718).
* (a) time and space complexity versus the number of vertices for the benchmarked graphs.
* (b) The computation time for calculating the MIS size and for counting the number of all independent sets (ISs), the number of MISs, the number of independent sets having size ``\alpha(G)`` and ``\alpha(G)-1``, and finding 100 largest set sizes.
* (c) The computation time for calculating the independence polynomials with different approaches.
* (d) The computation time for configuration enumeration, including single MIS configuration, the enumeration of all independent set configurations, all MIS configurations, all independent sets, and all independent set configurations having size ``\alpha(G)`` and ``\alpha(G)-1``.
The graphs in all benchmarks are random three-regular graphs, which have treewidth that is asymptotically smaller than ``|V|/6``. In this benchmark, we do not include traditional algorithms for finding the MIS sizes such as branching or dynamic programming. To the best of our knowledge, these algorithms are not suitable for computing most of the solution space properties mentioned in this paper. The main goal of this section is to show the relative computation time for calculating different solution space properties.
Panel (a) shows the time and space complexity of tensor network contraction for different graph sizes. The contraction order is obtained using the `TreeSA` algorithm that implemented in [OMEinsumContractionOrders](https://github.com/TensorBFS/OMEinsumContractionOrders.jl). If we assume our contraction-order finding program has found the optimal treewidth, which is very likely to be true, the space complexity is the same as the treewidth of the problem graph.
Slicing technique has been used for graphs with space complexity greater than ``2^{27}`` (above the yellow dashed line) to fit the computation into a 16GB memory. One can see that all the computation times in panels (b), (c), and (d) have a strong correlation with the predicted time and space complexity.
While in panel (d), the computation time of configuration enumeration also strongly correlates with other factors such as the configuration space size.
Among these benchmarks, computational tasks with data types real numbers, complex numbers, or [`Tropical`](@ref) numbers (CPU only) can utilize fast basic linear algebra subprograms (BLAS) functions. These tasks usually compute much faster than ones with other element types in the same category.
Immutable data types with no reference to other values can be compiled to GPU devices that run much faster than CPUs in all cases when the problem scale is big enough.
These data types do not include those defined in [`Polynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomial-2), [`ConfigEnumerator`](@ref), [`ExtendedTropical`](@ref) and [`SumProductTree`](@ref) or a data type containing them as a part.
In panel (c), one can see the Fourier transformation-based method is the fastest in computing the independence polynomial,
but it may suffer from round-off errors. The finite field (GF(p)) approach is the only method that does not have round-off errors and can be run on a GPU.
In panel (d), one can see the technique to bound the enumeration space (see paper) improves the performance for more than one order of magnitude in enumerating the MISs. The bounding technique can also reduce the memory usage significantly, without which the largest computable graph size is only ``\sim150`` on a device with 32GB main memory.
We show the benchmark of computing the maximal independent set properties on 3-regular graphs in the following plot,
including a comparison to the Bron-Kerbosch algorithm from Julia package [Graphs](https://github.com/JuliaGraphs/Graphs.jl)

In this plot, benchmarks of computing different solution space properties of the maximal independent sets (ISs) problem on random three regular graphs at different sizes.
* (a) time and space complexity of tensor network contraction.
* (b) The wall clock time for counting and enumeration of maximal ISs.
Panel (a) shows the space and time complexities of tensor contraction, which are typically larger than those for the independent set problem.
In panel (b), one can see counting maximal independent sets are much more efficient than enumerating them, while our generic tensor network approach runs slightly faster than the Bron-Kerbosch approach in enumerating all maximal independent sets.
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 2940 | # References
## Graph problems
```@docs
solve
GenericTensorNetwork
GraphProblem
IndependentSet
MaximalIS
Matching
Coloring
DominatingSet
SpinGlass
MaxCut
PaintShop
Satisfiability
SetCovering
SetPacking
OpenPitMining
```
#### Graph Problem Interfaces
To subtype [`GraphProblem`](@ref), a new type must contain a `code` field to represent the (optimized) tensor network.
Interfaces [`GenericTensorNetworks.generate_tensors`](@ref), [`labels`](@ref), [`flavors`](@ref) and [`get_weights`](@ref) are required.
[`nflavor`](@ref) is optional.
```@docs
GenericTensorNetworks.generate_tensors
labels
energy_terms
flavors
get_weights
chweights
nflavor
fixedvertices
```
#### Graph Problem Utilities
```@docs
is_independent_set
is_maximal_independent_set
is_dominating_set
is_vertex_coloring
is_matching
is_set_covering
is_set_packing
cut_size
spinglass_energy
num_paint_shop_color_switch
paint_shop_coloring_from_config
mis_compactify!
CNF
CNFClause
BoolVar
satisfiable
@bools
∨
¬
∧
is_valid_mining
print_mining
```
## Properties
```@docs
PartitionFunction
SizeMax
SizeMin
CountingAll
CountingMax
CountingMin
GraphPolynomial
SingleConfigMax
SingleConfigMin
ConfigsAll
ConfigsMax
ConfigsMin
```
## Element Algebras
```@docs
is_commutative_semiring
```
```@docs
TropicalNumbers.Tropical
TropicalNumbers.CountingTropical
ExtendedTropical
GenericTensorNetworks.Mods.Mod
TruncatedPoly
Max2Poly
ConfigEnumerator
SumProductTree
ConfigSampler
```
`GenericTensorNetworks` also exports the [`Polynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomial-2) and [`LaurentPolynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomials.LaurentPolynomial) types defined in package `Polynomials`.
For reading the properties from the above element types, one can use the following functions.
```@docs
read_size
read_count
read_config
read_size_count
read_size_config
```
The following functions are for saving and loading configurations.
```@docs
StaticBitVector
StaticElementVector
OnehotVec
save_configs
load_configs
save_sumproduct
load_sumproduct
@bv_str
onehotv
generate_samples
hamming_distribution
```
## Tensor Network
```@docs
optimize_code
getixsv
getiyv
contraction_complexity
estimate_memory
@ein_str
GreedyMethod
TreeSA
SABipartite
KaHyParBipartite
MergeVectors
MergeGreedy
```
## Others
#### Graph
```@docs
show_graph
show_configs
show_einsum
show_landscape
GraphDisplayConfig
AbstractLayout
SpringLayout
StressLayout
SpectralLayout
Layered
LayeredSpringLayout
LayeredStressLayout
render_locs
diagonal_coupled_graph
square_lattice_graph
unit_disk_graph
line_graph
random_diagonal_coupled_graph
random_square_lattice_graph
```
One can also use `random_regular_graph` and `smallgraph` in [Graphs](https://github.com/JuliaGraphs/Graphs.jl) to build special graphs.
#### Multiprocessing
```@docs
GenericTensorNetworks.SimpleMultiprocessing.multiprocess_run
``` | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 1609 | # Sum product representation for configurations
[`SumProductTree`](@ref) can use polynomial memory to store exponential number of configurations.
It is a sum-product expression tree to store [`ConfigEnumerator`](@ref) in a lazy style, where configurations can be extracted by depth first searching the tree with the `Base.collect` method.
Although it is space efficient, it is in general not easy to extract information from it due to the exponential large configuration space.
Directed sampling is one of its most important operations, with which one can get some statistic properties from it with an intermediate effort. For example, if we want to check some property of an intermediate scale graph, one can type
```@repl sumproduct
using GenericTensorNetworks
graph = random_regular_graph(70, 3)
problem = GenericTensorNetwork(IndependentSet(graph); optimizer=TreeSA());
tree = solve(problem, ConfigsAll(; tree_storage=true))[]
```
If one wants to store these configurations, he will need a hard disk of size 256 TB!
However, this sum-product binary tree structure supports efficient and unbiased direct sampling.
```@repl sumproduct
samples = generate_samples(tree, 1000)
```
With these samples, one can already compute useful properties like Hamming distance (see [`hamming_distribution`](@ref)) distribution. The following code visualizes this distribution with `CairoMakie`.
```@example sumproduct
using CairoMakie
dist = hamming_distribution(samples, samples)
# bar plot
fig = Figure()
ax = Axis(fig[1, 1]; xlabel="Hamming distance", ylabel="Frequency")
barplot!(ax, 0:length(dist)-1, dist)
fig
``` | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | docs | 285 | # Mods
Modular arithmetic for Julia.
This folder is a copy of v1.3.4 of the package `Mods.jl` by Ed Scheinerman, which is available at:
https://github.com/scheinerman/Mods.jl
We will switch back to the Github repo when the package becomes compatible with `GenericTensorNetworks.jl`. | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"MIT"
] | 0.1.1 | 39f992e4bb21d84030248d4bf68187dbbda402f7 | code | 2411 | module FixYourWorkaround
using Pkg
using Pkg.Types: VersionSpec, semver_spec
using Test
export package_compatible
export CompatNotFound, PackageNotInCompat, VersionNotCompatible
struct CompatNotFound <: Exception
message::String
end
Base.showerror(io::IO, e::CompatNotFound) = println(io, e.message)
struct PackageNotInCompat <: Exception
message::String
end
Base.showerror(io::IO, e::PackageNotInCompat) = println(io, e.message)
struct VersionNotCompatible <: Exception
message::String
end
Base.showerror(io::IO, e::VersionNotCompatible) = println(io, e.message)
"""
package_compatible(package_name::String, version::String)
Check to see if package_name@version is inbounds with the compat section in your Project.toml
# Arguments
- `package_name::String`: Name of the package
- `version::String`: Package version to check being inbounds
# Keywords
- `toml_path::String`: Path to the Project.toml file
# Returns
- `Bool`: If the version is in the compat versions
# Throws
- `PackageNotInCompat`: package_name was not found in the compat section
- `CompatNotFound`: Compat section not found in the Project.toml
- `VersionOutsideSpec`: Version is no longer inbounds of the compat versions
"""
function package_compatible(package_name::String, version::String; toml_path=joinpath(@__DIR__, "..", "Project.toml"))
version = VersionSpec(version)
toml = Pkg.TOML.parsefile(toml_path)
if haskey(toml, "compat")
if haskey(toml["compat"], package_name)
compat_version = semver_spec(toml["compat"][package_name])
if !isempty(intersect(version, compat_version))
return true
else
throw(VersionNotCompatible("$package_name@$version is not support"))
end
else
throw(PackageNotInCompat("$package_name not found in compat section"))
end
else
throw(CompatNotFound("Compat section not found in Project.toml"))
end
return false
end
package_compatible(package_name::String, version::Int64; kwargs...) = package_compatible(package_name, string(version); kwargs...)
package_compatible(package_name::String, version::Float64; kwargs...) = package_compatible(package_name, string(version); kwargs...)
package_compatible(package_name::String, version::VersionNumber; kwargs...) = package_compatible(package_name, string(version); kwargs...)
end # module
| FixYourWorkaround | https://github.com/mattBrzezinski/FixYourWorkaround.jl.git |
|
[
"MIT"
] | 0.1.1 | 39f992e4bb21d84030248d4bf68187dbbda402f7 | code | 1633 | using FixYourWorkaround
using Test
package_name = "package"
dir = mktempdir()
toml_path = joinpath(dir, "Project.toml")
@testset "Exceptions" begin
@testset "CompatNotFound" begin
write(toml_path, "")
@test_throws CompatNotFound package_compatible(package_name, "0.0"; toml_path=toml_path)
end
@testset "PackageNotInCompat" begin
write(toml_path, "[compat]")
@test_throws PackageNotInCompat package_compatible(package_name, "0.0"; toml_path=toml_path)
end
end
@testset "Package outside of Versions" begin
write(
toml_path,
"""
[compat]
$package_name = "1"
"""
)
@test_throws VersionNotCompatible package_compatible(package_name, "0.0"; toml_path=toml_path)
end
@testset "Package in Versions" begin
write(
toml_path,
"""
[compat]
$package_name = "1"
"""
)
@test package_compatible(package_name, "1.1"; toml_path=toml_path)
end
@testset "Version::Int64" begin
write(
toml_path,
"""
[compat]
$package_name = "1"
"""
)
@test package_compatible(package_name, 1; toml_path=toml_path)
end
@testset "Version::Float64" begin
write(
toml_path,
"""
[compat]
$package_name = "1"
"""
)
@test package_compatible(package_name, 1.0; toml_path=toml_path)
end
@testset "Version::VersionNumber" begin
write(
toml_path,
"""
[compat]
$package_name = "1"
"""
)
@test package_compatible(package_name, v"1"; toml_path=toml_path)
end
| FixYourWorkaround | https://github.com/mattBrzezinski/FixYourWorkaround.jl.git |
|
[
"MIT"
] | 0.1.1 | 39f992e4bb21d84030248d4bf68187dbbda402f7 | docs | 1097 | ## Fix Your Workaround.jl
[](https://github.com/invenia/BlueStyle)
[](https://coveralls.io/github/mattBrzezinski/FixYourWorkaround.jl?branch=MB/travis)
[](https://github.com/SciML/ColPrac)
Have you ever created a work around because of a specific dependency version?
This package is a test utility to ensure you remember to fix your workaround after support for it has been dropped.
Whenever you create a workaround and plan to remove it after you drop version support for a package create a new test like so:
```julia
using FixYourWorkaround
@test package_compatible("Package", "Version")
```
In the future when you remove the version from the `compat` section of your Project.toml this test will fail and remind you to remove your workaround.
| FixYourWorkaround | https://github.com/mattBrzezinski/FixYourWorkaround.jl.git |
|
[
"MIT"
] | 0.1.1 | a1f3ac34b66e34553f1e0961b8eeef572d6c4525 | code | 6876 | module SwapLiterals
@static if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@optlevel"))
Base.Experimental.@optlevel 0
end
export @swapliterals
const FLOATS_USE_RATIONALIZE = Ref(false)
makedict(@nospecialize(pairs)) =
foldl(Base.ImmutableDict, pairs; init=Base.ImmutableDict{Any,Any}())
makedict(@nospecialize(pairs::AbstractDict)) = pairs
const defaultswaps =
let swaps = Any[Float64 => "@big_str",
Int => :big,
Int128 => :big]
if Int === Int32
push!(swaps, Int64 => :big)
end
makedict(swaps)
end
"""
floats_use_rationalize!(yesno::Bool=true)
If `true`, a `Float64` input is first converted to `Rational{Int}`
via `rationalize` before being further transformed.
"""
floats_use_rationalize!(yesno::Bool=true) = FLOATS_USE_RATIONALIZE[] = yesno
# swaps is a collection of pairs
function literals_swapper(swaps)
@nospecialize
swaps = makedict(swaps)
# Base.Callable might be overly restrictive for callables, this check should
# probably be removed eventually
all(kv -> kv[2] isa Union{String,Symbol,Nothing,Base.Callable}, swaps) ||
throw(ArgumentError("unsupported type for swapper"))
foreach(swaps) do kv
kv[1] ∈ Any[Float32,Float64,Int32,Int64,String,Char,
Base.BitUnsigned64_types...,Int128,UInt128,BigInt,
:braces, :bracescat, :tuple, :vect, :(:=)] ||
throw(ArgumentError("type $(kv[1]) cannot be replaced"))
end
function swapper(@nospecialize(ex::Union{Float32,Float64,Int32,Int64,String,Char,
Base.BitUnsigned64}), quoted=false)
swap = get(swaps, typeof(ex), nothing)
if swap === nothing
requote(ex, quoted)
elseif quoted
ex
elseif swap isa String
Expr(:macrocall, Symbol(swap), nothing, string(ex))
elseif ex isa AbstractFloat && FLOATS_USE_RATIONALIZE[]
if swap == :big # big(1//2) doesn't return BigFloat
swap = :BigFloat
end
:($swap(rationalize($ex)))
elseif swap isa Symbol
:($swap($ex))
else
swap(ex)
end
end
function swapper(@nospecialize(ex::Expr), quoted=false)
h = ex.head
if h == :macrocall &&
ex.args[1] isa GlobalRef &&
ex.args[1].name ∈ (Symbol("@int128_str"),
Symbol("@uint128_str"),
Symbol("@big_str"))
swap = get(swaps,
ex.args[1].name == Symbol("@big_str") ? BigInt :
ex.args[1].name == Symbol("@int128_str") ? Int128 : UInt128,
nothing)
if swap === nothing
requote(ex, quoted)
elseif quoted
ex
else
if swap == :big
swap = "@big_str"
end
if swap isa String
ex.args[1] = Symbol(swap)
ex
elseif swap isa Symbol
:($swap($ex))
else
swap(ex)
end
end
elseif h ∈ (:braces, :bracescat, :tuple, :vect, :(:=))
ex = recswap(ex)
swap = get(swaps, h, nothing)
if swap === nothing
requote(ex, quoted)
elseif quoted
ex
elseif swap isa Symbol
:($swap($ex))
else
swap(ex)
end
else
ex = recswap(ex)
if quoted
Expr(:$, ex)
else
ex
end
end
end
function recswap(@nospecialize(ex))
h = ex.head
# copied from REPL.softscope
if h in (:meta, :import, :using, :export, :module, :error, :incomplete, :thunk)
ex
elseif Meta.isexpr(ex, :$, 1)
swapper(ex.args[1], true)
else
ex′ = Expr(h)
map!(swapper, resize!(ex′.args, length(ex.args)), ex.args)
ex′
end
end
requote(@nospecialize(ex), quoted) = quoted ? Expr(:$, ex) : ex
swapper(@nospecialize(ex), quoted=false) = requote(ex, quoted)
swapper
end
# to save time loading SafeREPL
const default_literals_swapper = literals_swapper(defaultswaps)
## macro
transform_arg(mod, @nospecialize(x)) =
if x isa QuoteNode
x.value
elseif x == :nothing
nothing
elseif x isa String
x
elseif x isa Symbol
getfield(mod, x)
elseif x isa Expr
swap = mod.eval(x)
ex -> Base.invokelatest(swap, ex)
else
throw(ArgumentError("invalid swapper type: $(typeof(x))"))
end
macro swapliterals(swaps...)
length(swaps) == 1 &&
return literals_swapper(defaultswaps)(esc(swaps[1]))
if length(swaps) == 2 && swaps[1] isa Expr && swaps[1].head == :vect
swaps = Any[swaps[1].args..., swaps[2]]
end
# either there are pairs/keyword arguments (handled first),
# or positional arguments (handled second), but not both
if swaps[1] isa Expr
ex = esc(swaps[end])
swaps = swaps[1:end-1]
transform_src(x::Symbol) = getfield(Base, x)
transform_src(x::QuoteNode) = x.value # for `:braces`, etc.
if Meta.isexpr(swaps[1], :call, 3) # pairs
swaps = map(swaps) do sw
Meta.isexpr(sw, :call, 3) && sw.args[1] == :(=>) ||
throw(ArgumentError("invalid pair argument"))
transform_src(sw.args[2]) => sw.args[3]
end
else
swaps = map(swaps) do sw # keyword arguments
Meta.isexpr(sw, :(=), 2) ||
throw(ArgumentError("invalid keyword argument"))
transform_src(sw.args[1]) => sw.args[2]
end
end
else
for a in swaps[1:end-1]
a isa Union{QuoteNode,String} || a == :nothing ||
throw(ArgumentError("invalid argument: $a"))
end
ex = esc(swaps[end])
if length(swaps) == 4
swaps = Any[Float64=>swaps[1], Int=>swaps[2], Int128=>swaps[3]]
elseif length(swaps) == 5
swaps = Any[Float64=>swaps[1], Int=>swaps[2], Int128=>swaps[3], BigInt=>swaps[4]]
else
throw(ArgumentError("wrong number of arguments"))
end
if Int !== Int64
# transform Int64 in the same way we transform Int == Int32
push!(swaps, Int64 => last(swaps[2]))
end
end
swaps = Any[k => transform_arg(__module__, v) for (k, v) in swaps]
literals_swapper(swaps)(ex)
end
end # module
| SafeREPL | https://github.com/rfourquet/SafeREPL.jl.git |
|
[
"MIT"
] | 0.1.1 | a1f3ac34b66e34553f1e0961b8eeef572d6c4525 | code | 11712 | using Test
using SwapLiterals
using SwapLiterals: floats_use_rationalize!
using BitIntegers, SaferIntegers
literalswapper(sw::Pair...) = SwapLiterals.literals_swapper(sw)
literalswapper(F, I, I128, B=nothing) =
literalswapper(Float64=>F, Int=>I, Int128=>I128, BigInt=>B)
makeset(ex) = Expr(:call, :Set, Expr(:vect, ex.args...))
# just a random function, which transform `a := x` into `A := x`
makecoloneq(ex) = Expr(:(=),
Symbol(uppercase(String(ex.args[1]))),
ex.args[2:end]...)
@testset "swapliterals" begin
swapbig = literalswapper(:BigFloat, :big, "@big_str")
@test swapbig(1) == :(big(1))
@test swapbig(1.2) == :(BigFloat(1.2))
@swapliterals :BigFloat :big "@big_str" begin
@test 1 == Int(1)
@test 1 isa BigInt
@test 10000000000 isa BigInt # Int64 literals are transformed like Int literals
@test 1.2 isa BigFloat
@test 1.2 == big"1.1999999999999999555910790149937383830547332763671875"
@test 1.0 == Float64(1.0)
@test $1 isa Int
@test $10000000000 isa Int64 # even on 32-bits systems
@test $1.2 isa Float64
end
# next three blocs should be equivalent
@swapliterals begin
@test 1.2 isa BigFloat
@test 1.2 == big"1.2"
@test 1 isa BigInt
@test 10000000000 isa BigInt # Int64 literals are transformed like Int literals
@test 11111111111111111111 isa BigInt
end
@swapliterals "@big_str" :big :big begin
@test 1.2 isa BigFloat
@test 1.2 == big"1.2"
@test 1 isa BigInt
@test 11111111111111111111 isa BigInt
end
@swapliterals Float64=>"@big_str" Int=>:big Int128=>:big begin
@test 1.2 isa BigFloat
@test 1.2 == big"1.2"
@test 1 isa BigInt
if Int === Int64
@test 10000000000 isa BigInt
else
@test 10000000000 isa Int64 # Int64 literals are *not* transformed like Int literals
end
@test 11111111111111111111 isa BigInt
end
@swapliterals Int64 => :big begin
if Int === Int64
@test 1 isa BigInt
else
@test 1 isa Int
end
@test 10000000000 isa BigInt
end
# TODO: these tests in loop are dubious
for T in Base.BitUnsigned_types
@test typeof(swapbig(T(1))) == T
end
for T in [Float32, Float16]
@test typeof(swapbig(T(1))) == T
end
x = eval(swapbig(1.0))
@test x isa BigFloat && x == 1.0
x = eval(swapbig(1))
@test x == 1 && x isa BigInt
x = eval(swapbig(:11111111111111111111))
@test x == 11111111111111111111 && x isa BigInt
x = eval(swapbig(:1111111111111111111111111111111111111111))
@test x isa BigInt
@swapliterals :BigFloat :big "@big_str" begin
x = 1.0
@test x isa BigFloat && x == Float64(1.0)
x = 1
@test x == Int(1) && x isa BigInt
x = 11111111111111111111
@test x == big"11111111111111111111" && x isa BigInt
x = 1111111111111111111111111111111111111111
@test x isa BigInt
@test $1.0 isa Float64
@test $11111111111111111111 isa Int128
# throws as un-handled quote
# @test $1111111111111111111111111111111111111111 isa BigInt
end
swap128 = literalswapper(:Float64, :Int128, "@int128_str")
x = eval(swap128(1))
@test x == 1 && x isa Int128
x = eval(swap128(:11111111111111111111))
@test x == 11111111111111111111 && x isa Int128
x = eval(swap128(:1111111111111111111111111111111111111111))
@test x isa BigInt
@swapliterals :Float64 :Int128 "@int128_str" begin
x = 1
@test x == Int(1) && x isa Int128
x = 10000000000
@test x == big"10000000000"
@test x isa Int128 # Int64 literals are transformed like Int literals
x = 11111111111111111111
@test x == Int128(11111111111111111111) && x isa Int128
x = 1111111111111111111111111111111111111111
@test x isa BigInt
end
swapnothing = literalswapper(nothing, nothing, nothing)
x = eval(swapnothing(1.0))
@test x isa Float64
x = eval(swapnothing(:11111111111111111111))
@test x isa Int128
x = eval(swapnothing(:1111111111111111111111111111111111111111))
@test x isa BigInt
@swapliterals nothing nothing nothing begin
x = 1.0
@test x isa Float64
@test 1 isa Int
@test 10000000000 isa Int64
x = 11111111111111111111
@test x isa Int128
x = 1111111111111111111111111111111111111111
@test x isa BigInt
end
# pass :big instead of a string macro
swaponly128 = literalswapper(nothing, nothing, :big)
x = eval(swaponly128(:11111111111111111111))
@test x isa BigInt
@swapliterals nothing nothing :big begin
x = 11111111111111111111
@test x isa BigInt
end
# pass symbol for Int128
swapBitIntegers = literalswapper(nothing, :Int256, :Int256)
x = eval(swapBitIntegers(123))
@test x isa Int256
x = eval(swapBitIntegers(:11111111111111111111))
@test x isa Int256
swapSaferIntegers = literalswapper(nothing, :SafeInt, :SafeInt128)
x = eval(swapSaferIntegers(123))
@test x isa SafeInt
x = eval(swapSaferIntegers(:11111111111111111111))
@test x isa SafeInt128
@swapliterals nothing :Int256 :Int256 begin
x = 123
@test x isa Int256
x = 11111111111111111111
@test x isa Int256
end
@swapliterals nothing :SafeInt :SafeInt128 begin
x = 123
@test x isa SafeInt
x = 11111111111111111111
@test x isa SafeInt128
end
# pass symbol for BigInt
swapbig = literalswapper(nothing, nothing, :Int1024, :Int1024)
x = eval(swapbig(:11111111111111111111))
@test x isa Int1024
x = eval(swapbig(:1111111111111111111111111111111111111111))
@test x isa Int1024
@swapliterals nothing nothing :Int1024 :Int1024 begin
@test 11111111111111111111 isa Int1024
@test 1111111111111111111111111111111111111111 isa Int1024
@test $11111111111111111111 isa Int128
@test $1111111111111111111111111111111111111111 isa BigInt
end
swapbig = literalswapper(nothing, nothing, :big, :big)
x = eval(swapbig(:11111111111111111111))
@test x isa BigInt
x = eval(swapbig(:1111111111111111111111111111111111111111))
@test x isa BigInt
@swapliterals nothing nothing :big :big begin
x = 11111111111111111111
@test x isa BigInt
x = 1111111111111111111111111111111111111111
@test x isa BigInt
end
# kwargs
kwswapper = literalswapper(Int=>:big)
@test eval(kwswapper(1.2)) isa Float64
@test eval(kwswapper(1)) isa BigInt
@test eval(kwswapper(:11111111111111111111)) isa Int128
@test eval(kwswapper(:1111111111111111111111111111111111111111)) isa BigInt
# Float32
@swapliterals Float32 => :big begin
@test 1.2f0 == big"1.2000000476837158203125"
end
@swapliterals Float32 => "@big_str" begin
@test 1.2f0 == big"1.2"
end
# string swappers
@swapliterals Int => "@big_str" UInt8 => "@raw_str" begin
@test 1 isa BigInt
@test 0x01 === "1"
end
# Int & UInt
@swapliterals Int => :UInt8 UInt => :Int8 begin
@test 1 isa UInt8
if UInt === UInt64
@test 0x0000000000000001 isa Int8
@test 0x00000001 isa UInt32
else
@test 0x00000001 isa Int8
@test 0x0000000000000001 isa UInt64
end
end
@swapliterals Int32=>:UInt8 Int64=>:UInt8 UInt64=>:Int8 begin
@test 1 isa UInt8
@test 0x0000000000000001 isa Int8
end
# unsigned
@swapliterals UInt8=>:Int UInt16=>:Int UInt32=>:Int UInt64=>:Int UInt128=>:Int128 begin
@test 0x1 isa Int
@test 0x0001 isa Int
@test $0x0001 isa UInt16
@test 0x00000001 isa Int
@test $0x00000001 isa UInt32
@test :0x00000001 isa UInt32
@test 0x0000000000000001 isa Int
@test :0x0000000000000001 isa UInt64
@test 0x00000000000000000000000000000001 isa Int128
@test $0x00000000000000000000000000000001 isa UInt128
end
@swapliterals UInt128=>"@int128_str" begin
@test 0x00000000000000000000000000000001 isa Int128
@test $0x00000000000000000000000000000001 isa UInt128
end
# strings & chars
@swapliterals Char=>:string String => "@r_str" begin
@test "123" isa Regex
@test 'a' isa String
end
@swapliterals Char => :UInt64 String => :Symbol begin
@test "123" isa Symbol
@test 'a' === 0x0000000000000061
end
@test_throws ArgumentError literalswapper(Array=>:Int)
# quoted expressions which are not handled by a swapper remain quoted
swapper = literalswapper(Char=>UInt)
@test 'a' !== swapper('a') == 0x61
@test swapper(Expr(:$, 'a')) === 'a'
@test_throws ErrorException eval(swapper(Expr(:$, 1)))
@test_throws ErrorException eval(swapper(Expr(:$, :11111111111111111111)))
@test_throws ErrorException eval(swapper(Expr(:$, :1111111111111111111111111111111111111111)))
# function swappers
@swapliterals UInt8 => (x -> x+1) Int => UInt8 Int128 => (ex -> ex.args[3]) begin
@test 0x01 == 2.0
@test 1 isa UInt8
@test 11111111111111111111 == "11111111111111111111"
end
# :braces, :tuple, :vect
@swapliterals [:braces => makeset,
:bracescat => makeset,
:tuple => makeset,
:vect => makeset
] begin
r = push!(Set{Int}(), 1, 2, 3)
s = {1, 2, 3}
@test s isa Set{Int}
@test s == r
s = [1, 2, 3]
@test s isa Set{Int}
@test s == r
s = (1, 2, 3)
@test s isa Set{Int}
@test s == r
s = { 1
2
3 }
@test s isa Set{Int}
@test s == r
end
@swapliterals :tuple => :collect begin
v = (1, 2, 3)
@test v isa Vector{Int}
@test v == [1, 2, 3]
end
# :(:=)
@swapliterals :(:=) => makecoloneq begin
a := 2
@test A == 2
@test !@isdefined(a)
bcd := 1, 2, 3
@test BCD == (1, 2, 3)
@test !@isdefined(bcd)
end
# test that swapper is applied recursively
@swapliterals :tuple => makeset Int => :big begin
@test (1, 2) isa Set{BigInt}
end
@swapliterals Int => :big begin
@test (1, 2) isa Tuple{BigInt,BigInt}
end
end
# test name resolution for functions
module TestModule
using SwapLiterals, Test
uint8(x) = UInt8(x)
@swapliterals Int => uint8 Char => (x -> uint8(x)+1) begin
@test 1 isa UInt8
@test 'a' == 0x62
end
end
## playing with floats_use_rationalize!()
# can't be in a @testset apparently, probably because the parsing
# in @testset is done before floats_use_rationalize!() takes effect
@swapliterals Float32="@big_str" Float64="@big_str" begin
@test 1.2 == big"1.2"
@test 1.2f0 == big"1.2"
end
floats_use_rationalize!()
@swapliterals Float32="@big_str" Float64="@big_str" begin
@test 1.2 == big"1.2"
@test 1.2f0 == big"1.2"
end
# try again, with explicit `true` arg, and with :BigFloat instead of :big
floats_use_rationalize!(true)
@swapliterals Float32=:BigFloat Float64=:BigFloat begin
@test 1.2 == big"1.2"
@test 1.2f0 == big"1.2"
end
floats_use_rationalize!(false)
@swapliterals Float32=:BigFloat Float64=:BigFloat begin
@test 1.2 == big"1.1999999999999999555910790149937383830547332763671875"
@test 1.2f0 == big"1.2000000476837158203125"
end
| SafeREPL | https://github.com/rfourquet/SafeREPL.jl.git |
|
[
"MIT"
] | 0.1.1 | a1f3ac34b66e34553f1e0961b8eeef572d6c4525 | code | 2623 | module SafeREPL
Base.Experimental.@optlevel 0
export swapliterals!
using SwapLiterals: SwapLiterals, makedict, floats_use_rationalize!,
literals_swapper, default_literals_swapper, defaultswaps
using REPL
function __init__()
# condensed equivalent version of `swapliterals!()`, for faster loading
push!(get_transforms(), default_literals_swapper)
end
const LAST_SWAPPER = Ref{Function}(default_literals_swapper)
function get_transforms()
if isdefined(Base, :active_repl_backend) &&
isdefined(Base.active_repl_backend, :ast_transforms)
Base.active_repl_backend.ast_transforms::Vector{Any}
else
REPL.repl_ast_transforms::Vector{Any}
end
end
"""
SafeREPL.swapliterals!(Float64, Int, Int128, BigInt=nothing)
Specify transformations for literals:
argument `Float64` corresponds to literals of type `Float64`, etcetera.
!!! note
On 32-bits systems, the transformation for `Int` is also applied on
`Int64` literals.
A transformation can be
* a `Symbol`, to refer to a function, e.g. `:big`;
* `nothing` to not transform literals of this type;
* a `String` specifying the name of a string macro, e.g. `"@big_str"`,
which will be applied to the input. Available only for
`Int128` and `BigInt`, and experimentally for `Float64`.
"""
function swapliterals!(Float64,
Int,
Int128,
BigInt=nothing)
@nospecialize
if Base.Int === Base.Int64
swapliterals!(; Float64, Int, Int128, BigInt)
else
swapliterals!(; Float64, Int, Int64=Int, Int128, BigInt)
end
end
function swapliterals!(@nospecialize(swaps::AbstractDict))
swapliterals!(false) # remove previous settings
LAST_SWAPPER[] = swaps === defaultswaps ? default_literals_swapper :
literals_swapper(swaps)
push!(get_transforms(), LAST_SWAPPER[])
nothing
end
# called only when !isempty(swaps)
swapliterals!(swaps::Pair...) = swapliterals!(makedict(swaps))
# non-public API when !isempty(kwswaps)
function swapliterals!(; kwswaps...)
swapliterals!(
isempty(kwswaps) ?
defaultswaps :
makedict(Any[getfield(Base, first(sw)) => last(sw) for sw in kwswaps]))
end
function swapliterals!(activate::Bool)
transforms = get_transforms()
# first always de-activate
filter!(f -> parentmodule(f) != SwapLiterals, transforms)
if activate
push!(transforms, LAST_SWAPPER[])
end
nothing
end
isactive() = any(==(SwapLiterals) ∘ parentmodule, get_transforms())
end # module
| SafeREPL | https://github.com/rfourquet/SafeREPL.jl.git |
|
[
"MIT"
] | 0.1.1 | a1f3ac34b66e34553f1e0961b8eeef572d6c4525 | code | 101 | using Pkg
if VERSION >= v"1.5"
Pkg.develop(path="../SwapLiterals")
end
Pkg.test("SwapLiterals")
| SafeREPL | https://github.com/rfourquet/SafeREPL.jl.git |
|
[
"MIT"
] | 0.1.1 | a1f3ac34b66e34553f1e0961b8eeef572d6c4525 | docs | 15714 | [](https://travis-ci.org/rfourquet/SafeREPL.jl)
## SafeREPL
The `SafeREPL` package allows to swap, in the REPL, the meaning of Julia's
literals (in particular numbers).
Upon loading, the default is to replace `Float64` literals with `BigFloat`,
and `Int`, `Int64` and `Int128` literals with `BigInt`.
A literal prefixed with `$` is left unchanged.
```julia
julia> using SafeREPL
julia> 2^200
1606938044258990275541962092341162602522202993782792835301376
julia> sqrt(2.0)
1.414213562373095048801688724209698078569671875376948073176679737990732478462102
julia> typeof($2)
Int64
```
### Installation
This package requires Julia version at least 1.5. It depends on a sub-package,
`SwapLiterals`, described below, which requires only Julia 1.1.
Both packages are registered and can be installed via
```julia
using Pkg
pkg"add SafeREPL"
pkg"add SwapLiterals"
```
### Custom types
What literals mean is specified via `SafeREPL.swapliterals!`.
The four arguments of this function correspond to
`Float64`, `Int`, `Int128`, `BigInt`.
Passing `nothing` means not transforming literals of this type, and
a symbol is interpreted as the name of a function to be applied to the value.
The last argument defaults to `nothing`.
On 32-bits systems, `Int64` literals are transformed in the same way as `Int`
literals.
A single boolean value can also be passed: `swapliterals!(false)` deactivates
`SafeREPL` and `swapliterals!(true)` re-activates it with the previous setting.
Finally, `swapliterals!()` activates the default setting
(what is enabled with `using SafeREPL`, which is equivalent to
`swapliterals!("@big_str", :big, :big)`, see [below](#string-macros)
for the meaning of `"@big_str"`).
#### Examples
```julia
julia> using BitIntegers, BitFloats
julia> swapliterals!(:Float128, :Int256, :Int256)
julia> log2(factorial(60))
254.8391546883338
julia> sqrt(2.0)
1.41421356237309504880168872420969798
julia> using SaferIntegers, DoubleFloats
julia> swapliterals!(:DoubleFloat, :SafeInt, :SafeInt128)
julia> typeof(2.0)
Double64
julia> 2^64
ERROR: OverflowError: 2^64
Stacktrace:
[...]
julia> 10000000000000000000^3
ERROR: OverflowError: 10000000000000000000 * 100000000000000000000000000000000000000 overflowed for type Int128
Stacktrace:
[...]
julia> using Nemo; swapliterals!(nothing, :fmpz, :fmpz, :fmpz)
julia> factorial(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
julia> typeof(ans), typeof(1.2)
(fmpz, Float64)
julia> [1, 2, 3][1] # fmpz is currently not <: Integer ...
ERROR: ArgumentError: invalid index: 1 of type fmpz
[...]
julia> [1, 2, 3][$1] # ... so quote array indices
1
julia> swapliterals!(false); typeof(1), typeof(1.0) # this swapliterals! doesn't act on this line!
(fmpz, Float64)
julia> typeof(1), typeof(1.0)
(Int64, Float64)
julia> swapliterals!(true)
julia> typeof(1), typeof(1.0)
(fmpz, Float64)
julia> swapliterals!() # activate defaults
julia> typeof(1), typeof(1.0)
(BigInt, BigFloat)
```
### How to substitute other literals?
The more general API of `swapliterals!` is to pass a list of pairs
`SourceType => converter`, where `SourceType` is the type on which `converter`
should be applied. For example:
```julia
julia> swapliterals!(Char => :string, Float32 => :Float64, UInt8 => :UInt)
julia> 'a', 1.2f0, 0x12
("a", 1.2000000476837158, 0x0000000000000012)
julia> using Strs; swapliterals!(String => :Str)
julia> typeof("a")
ASCIIStr
```
Notable exceptions are `Symbol` and `Bool` literals, which currently can't be
converted with `swapliterals!` (open an issue if you really need this
feature).
### String macros
For `Int128`, `UInt128` and `BigInt`, it's possible to pass the name of a
string macro (as a `String`) instead of a symbol.
In this case, the macro is used to directly interpret the number. For example:
```julia
julia> swapliterals!(Int128 => "@int1024_str", BigInt => "@int1024_str")
julia> typeof(111111111111111111111111111111111)
Int1024
julia> 1234...(many digits).....789 # of course very big numbers can't be input anymore!
ERROR: LoadError: OverflowError: overflow parsing "1234..."
[...]
```
As an experimental feature, when a string macro is passed to interpret `Float64`,
the input is then first converted to a `String` which is passed to the macro:
```julia
julia> swapliterals!()
julia> 2.6 - 0.7 - 1.9
2.220446049250313e-16
julia> swapliterals!(Float64 => "@big_str")
julia> 1.2
1.200000000000000000000000000000000000000000000000000000000000000000000000000007
julia> 1.2 == big"1.2"
true
julia> 1.1999999999999999 == big"1.1999999999999999"
false
julia> 2.6 - 0.7 - 1.9
-1.727233711018888925077270372560079914223200072887256277004740694033718360632485e-77
julia> using DecFP; swapliterals!(Float64 => "@d64_str")
julia> 2.6 - 0.7 - 1.9
0.0
```
### For the adventurous
<details>
<summary>Are you sure?</summary>
Few more literals can be substituted: arrays and tuples, and the `{}` vector
syntax, which are specified respectively as `:vect`, `:tuple`, `:braces`.
Vectors entered with `{}` delimiters but with elements separated with a newline
instead of `,` can be specified as `:bracescat`.
For example:
```julia
julia> swapliterals!(:vect => :Set)
julia> [1, 2]
Set{Int64} with 2 elements:
2
1
julia> :[1, 2]
:(Set([1, 2]))
julia> $[1, 2]
2-element Array{Int64,1}:
1
2
```
The next question is: how to use the `:braces` syntax, given that it is not
valid normal-Julia syntax? In addition to the previously mentioned
converter types (`Symbol` and `String`), it's possible to pass a function
which is used to transform the Julia AST:
```julia
julia> makeset(ex) = Expr(:call, :Set, Expr(:vect, ex.args...));
julia> swapliterals!(:braces => makeset, :bracescat => makeset)
julia> {1, 2, 3}
Set{Int64} with 3 elements:
2
3
1
julia> { 1
2 }
Set{Int64} with 2 elements:
2
1
```
For types which are stored directly in the AST, using a symbol or
a function is roughly equivalent (and using `$`-quoting or `:`-quoting
is similarly equivalent), for example:
```julia
julia> swapliterals!(Int => Float64)
julia> (1, :1, $1)
1.0, 1, 1
julia> :(1 + 2)
:(1.0 + 2.0)
julia> swapliterals!(Int => :Float64)
julia> (1, :1, $1)
1.0, 1, 1
julia> :(1 + 2)
:(Float64(1) + Float64(2))
```
Note that using functions is a rather experimental feature.
A natural question arising pretty quickly is how `$`-quoting interacts with
other `$`-quoting contexts, in particular with `BenchmarkTools`. With
scalar-substitutions, this is mostly a non-issue, as we usually do not
`$`-quote literal numbers while benchmarking, but this is a bit more subtle
when substituting container literals:
```julia
julia> swapliterals!(false)
julia> @btime sum([1, 2]);
31.520 ns (1 allocation: 96 bytes)
julia> @btime sum($[1, 2]);
3.129 ns (0 allocations: 0 bytes)
julia> @btime sum($(Set([1, 2])));
20.090 ns (0 allocations: 0 bytes)
julia> swapliterals!(:vect => makeset)
julia> @btime sum($[1, 2]); # $[1, 2] is really a vector
31.459 ns (1 allocation: 96 bytes)
julia> @btime sum($$[1, 2]); # BenchmarkTools-$-quoting for real [1, 2]
3.480 ns (0 allocations: 0 bytes)
julia> @btime sum($(begin [1, 2] end)); # BenchmarkTools-$-quoting for real Set([1, 2])
19.786 ns (0 allocations: 0 bytes)
julia> @btime sum($:[1, 2]) # ???
20.077 ns (0 allocations: 0 bytes)
```
Using a symbol versus a function can also have a subtle impact on benchmarking:
```julia
julia> swapliterals!(false)
julia> @btime big(1) + big(2);
176.467 ns (6 allocations: 128 bytes)
julia> @btime $(big(1)) + $(big(2));
71.681 ns (2 allocations: 48 bytes)
julia> swapliterals!(Int => :big)
julia> :(1 + 2)
:(big(1) + big(2))
julia> @btime 1 + 2
176.982 ns (6 allocations: 128 bytes)
julia> swapliterals!(Int => big)
julia> :(1 + 2)
:(1 + 2)
julia> dump(:(1 + 2))
Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol +
2: BigInt
alloc: Int32 1
size: Int32 1
d: Ptr{UInt64} @0x0000000004662760
3: BigInt
alloc: Int32 1
size: Int32 1
d: Ptr{UInt64} @0x000000000356d4a0
julia> @btime 1 + 2
63.765 ns (2 allocations: 48 bytes)
```
Finally, as an experimental feature, expressions involving `:=`
can also be transformed, with the same mechanism, for example:
```julia
julia> swapliterals!(:(:=) => ex -> Expr(:(=),
Symbol(uppercase(String(ex.args[1]))),
ex.args[2:end]...))
julia> a := 1; A # equivalent to `A = 1`
1
```
</details>
### How to use in source code?
Via the `@swapliterals` macro from the `SwapLiterals` package,
which has roughly the same API as the `swapliterals!` function:
```julia
using SwapLiterals
x = @swapliterals :big :big :big begin
1.0, 2^123
end
typeof(x) # Tuple{BigFloat,BigInt}
x = @swapliterals (1.0, 2^123) # shorter version, uses :big as defaults
```
Note: if you try the above at the REPL while `SafeREPL` is also active, `typeof(x)`
might be `Tuple{BigFloat,BigInt}`.
Try first `swapliterals!(false)` to deactivate `SafeREPL`.
The pair API is also available, as well as the possibility to pass converters in
a (literal) array for more clarity:
```julia
@swapliterals Int => :big 1
x = @swapliterals [Int => :big,
Int128 => :big,
Float64 => big
] begin
1.0, 1, 111111111111111111111
end
typeof(x) # Tuple{BigFloat,BigInt,BigInt}
```
Note that passing a non-global function as the converter
(to transform the AST, cf. [previous section](#for-the-adventurous))
is likely to fail.
### Visual indicator that SafeREPL is active
The following can be put in the "startup.jl" file to modify the color of the
prompt, or to modify the text in the prompt. Tweak as necessary.
```julia
using REPL
atreplinit() do repl
repl.interface = REPL.setup_interface(repl)
julia_mode = repl.interface.modes[1]
old_prefix = julia_mode.prompt_prefix
julia_mode.prompt_prefix = function()
if isdefined(Main, :SafeREPL) && SafeREPL.isactive()
Base.text_colors[:yellow]
else
old_prefix
end
end
old_prompt = julia_mode.prompt
julia_mode.prompt = function()
if isdefined(Main, :SafeREPL) && SafeREPL.isactive()
"safejulia> " # ;-)
else
old_prompt
end
end
end
```
### Switching easily back and forth
You can set up a keybinding to activate or de-activate `SafeREPL`, e.g.
`Ctrl-x` followed by `Ctrl-s`, by putting the following in "startup.jl":
```julia
using REPL
const mykeys = Dict(
"^x^s" => function (s, o...)
swapliterals!(!SafeREPL.isactive())
REPL.LineEdit.refresh_line(s)
end
)
atreplinit() do repl
repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
end
```
Cf. the
[manual](https://docs.julialang.org/en/v1.4/stdlib/REPL/#Customizing-keybindings-1)
for details.
Note that `REPL.setup_interface` should be called only once, so to set up
a keybinding together with a custom prompt as shown in last section,
both `atreplinit` calls must be combined, e.g.
```julia
atreplinit() do repl
repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
julia_mode = repl.interface.modes[1]
# ... modify julia_mode
end
```
### Caveats
* This package was not tested on 32-bits architectures, so use it at your own risks.
By the way, there is no guarantee even on 64-bits architectures...
* Using new number types by default in the REPL might reveal many missing methods
for these types and render the REPL less usable than ideal.
Good opportunity for opening ticket/issues in the corresponding projects :)
In the meantime, this can be mitigated by the use of `$`.
* It should be clear that using `BigInt` and `BigFloat` for literals instead
of `Int` and `Float64` can make some function calls quite more expensive,
time-wise and memory-wise. So `SafeREPL` just offers a different trade-off
than the default Julia REPL, it's not a panacea.
* float literals are stored as `Float64` in the Julia AST, meaning that
information can be lost:
```julia
julia> using SafeREPL; swapliterals!(Float64 => :big)
julia> :(print(1.2))
:(print(big(1.2)))
julia> 1.2 # this is equivalent to `big(1.2)`
1.1999999999999999555910790149937383830547332763671875
julia> big"1.2"
1.200000000000000000000000000000000000000000000000000000000000000000000000000007
```
As said earlier, one can pass `"@big_str"` for the `Float64` converter to try
to mitigate this problem: this is currently the default.
Another alternative (which does _not_ always produce
the same results as with `"@big_str"`) is to call `rationalize` before
converting to a float.
There is an experimental option to have `SafeREPL` implicitly insert
calls to `rationalize`, which is enabled by calling
`floats_use_rationalize!(true)`:
```julia
julia> bigfloat(x) = BigFloat(rationalize(x));
julia> swapliterals!(Float64 => :bigfloat)
julia> 1.2
1.200000000000000000000000000000000000000000000000000000000000000000000000000007
julia> swapliterals!(Float64 => :big); SafeREPL.floats_use_rationalize!(true);
julia> 1.2
1.200000000000000000000000000000000000000000000000000000000000000000000000000007
julia> 1.20000000000001
1.200000000000010169642905566151645987816694259698096594761182517957654980952429
julia> swapliterals!(Float64 => "@big_str") # rationalize not used
julia> 1.20000000000001
1.200000000000010000000000000000000000000000000000000000000000000000000000000006
```
### How "safe" is it?
This is totally up to the user. Some Julia users get disappointed when they
encounter some "unsafe" arithmetic operations (due to integer overflow for
example). "Safe" in `SafeREPL` must be understood tongue-in-cheek, and applies
to the default setting where some overflows will disappear. This package can
make Julia quite more unsafe; here is a "soft" example:
```julia
julia> swapliterals!(Int => x -> x % Int8)
julia> 1234
-46
```
### Alternatives
Before Julia 1.5, the easiest alternative was probably to use a custom REPL
mode, and
[ReplMaker.jl](https://github.com/MasonProtter/ReplMaker.jl#example-3-big-mode)
even has an example to set this up in few lines.
Here is a way to use `SwapLiterals` as a backend for a `ReplMaker` mode,
which uses the `valid_julia` function defined in its
[README](https://github.com/MasonProtter/ReplMaker.jl#example-1-expr-mode):
```julia
julia> literals_swapper = SwapLiterals.literals_swapper([Int=>:big, Int128=>:big, Float64=>"@big_str"]);
julia> function Big_parse(s)
expr = Meta.parse(s)
literals_swapper(expr)
end
julia> initrepl(Big_parse,
prompt_text="BigJulia> ",
prompt_color = :red,
start_key='>',
mode_name="Big-Mode",
valid_input_checker=valid_julia)
```
The `SwapLiterals.literals_swapper` function takes a list of pairs which have
the same meaning as in `swapliterals!`. Note that it's currently not part of the
public API of `SwapLiterals`.
At least a couple of packages have a macro similar to `@swapliterals`:
* [ChangePrecision.jl](https://github.com/stevengj/ChangePrecision.jl),
with the `@changeprecision` macro which reinterprets floating-point literals
but also some floats-producing functions like `rand()`.
* [SaferIntegers.jl](https://github.com/JeffreySarnoff/SaferIntegers.jl),
with the `@saferintegers` macro which wraps integers using `SaferIntegers`
types.
| SafeREPL | https://github.com/rfourquet/SafeREPL.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 23653 | # LibFTD2XX.jl - High Level Module
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
#
# This module contains methods and functions for interacting with D2XX devices.
# It calls functions from the submodule `Wrapper` which in turn call Functions
# from the FT D2XX library. See D2XX Programmer's Guide (FT_000071) for more
# information on that library.
module LibFTD2XX
# Enums
export FTOpenBy, OPEN_BY_SERIAL_NUMBER, OPEN_BY_DESCRIPTION
export FTWordLength, BITS_8, BITS_7
export FTStopBits, STOP_BITS_1, STOP_BITS_2
export FTParity, PARITY_NONE, PARITY_ODD, PARITY_EVEN, PARITY_MARK, PARITY_SPACE
export FTBitMode, MODE_RESET, MODE_ASYNC_BITBANG, MODE_MPSSE, MODE_SYNC_BITBANG,
MODE_MCU_EMULATION, MODE_FAST_OPTO, MODE_CBUS_BITBANG, MODE_SCS_FIFO
# Types and Constructors
export FT_HANDLE # Exported by .Wrapper
export D2XXException
export D2XXDevice, D2XXDevices
# Port communication functions
export baudrate, datacharacteristics, timeouts, status, driverversion
# Library Functions
export libversion
# D2XXDevice Accessor Functions
export deviceidx, deviceflags, devicetype, deviceid, locationid, serialnumber,
description, fthandle
include("util.jl")
include("wrapper.jl")
using .Wrapper
"""
@enum(
FTOpenBy,
OPEN_BY_SERIAL_NUMBER = FT_OPEN_BY_SERIAL_NUMBER,
OPEN_BY_DESCRIPTION = FT_OPEN_BY_DESCRIPTION)
For use with [`open`](@ref).
"""
@enum(
FTOpenBy,
OPEN_BY_SERIAL_NUMBER = FT_OPEN_BY_SERIAL_NUMBER,
OPEN_BY_DESCRIPTION = FT_OPEN_BY_DESCRIPTION)
"""
@enum(
FTWordLength,
BITS_8 = FT_BITS_8,
BITS_7 = FT_BITS_7)
For use with [`datacharacteristics`](@ref).
"""
@enum(
FTWordLength,
BITS_8 = FT_BITS_8,
BITS_7 = FT_BITS_7)
"""
@enum(
FTStopBits,
STOP_BITS_1 = FT_STOP_BITS_1,
STOP_BITS_2 = FT_STOP_BITS_2)
For use with [`datacharacteristics`](@ref).
"""
@enum(
FTStopBits,
STOP_BITS_1 = FT_STOP_BITS_1,
STOP_BITS_2 = FT_STOP_BITS_2)
"""
@enum(
FTParity,
PARITY_NONE = FT_PARITY_NONE,
PARITY_ODD = FT_PARITY_ODD,
PARITY_EVEN = FT_PARITY_EVEN,
PARITY_MARK = FT_PARITY_MARK,
PARITY_SPACE = FT_PARITY_SPACE)
For use with [`datacharacteristics`](@ref).
"""
@enum(
FTParity,
PARITY_NONE = FT_PARITY_NONE,
PARITY_ODD = FT_PARITY_ODD,
PARITY_EVEN = FT_PARITY_EVEN,
PARITY_MARK = FT_PARITY_MARK,
PARITY_SPACE = FT_PARITY_SPACE)
"""
@enum(
FTBitMode,
MODE_RESET = FT_MODE_RESET,
MODE_ASYNC_BITBANG = FT_MODE_ASYNC_BITBANG,
MODE_MPSSE = FT_MODE_MPSSE,
MODE_SYNC_BITBANG = FT_MODE_SYNC_BITBANG,
MODE_MCU_EMULATION = FT_MODE_MCU_EMULATION,
MODE_FAST_OPTO = FT_MODE_FAST_OPTO,
MODE_CBUS_BITBANG = FT_MODE_CBUS_BITBANG,
MODE_SCS_FIFO = FT_MODE_SCS_FIFO)
For use with [`bitmode`](@ref).
"""
@enum(
FTBitMode,
MODE_RESET = FT_MODE_RESET,
MODE_ASYNC_BITBANG = FT_MODE_ASYNC_BITBANG,
MODE_MPSSE = FT_MODE_MPSSE,
MODE_SYNC_BITBANG = FT_MODE_SYNC_BITBANG,
MODE_MCU_EMULATION = FT_MODE_MCU_EMULATION,
MODE_FAST_OPTO = FT_MODE_FAST_OPTO,
MODE_CBUS_BITBANG = FT_MODE_CBUS_BITBANG,
MODE_SCS_FIFO = FT_MODE_SCS_FIFO)
"""
D2XXException <: Exception
LibFTD2XX High-Level Library Error Type.
"""
struct D2XXException <: Exception
str::String
end
"""
struct D2XXDevice <: IO
Device identifier for a D2XX device.
See also: [`D2XXDevices`](@ref), [`deviceidx`](@ref), [`deviceflags`](@ref),
[`devicetype`](@ref), [`deviceid`](@ref), [`locationid`](@ref),
[`serialnumber`](@ref), [`description`](@ref), [`fthandle`](@ref).
"""
struct D2XXDevice <: IO
idx::Int
flags::Int
typ::Int
id::Int
locid::Int
serialnumber::String
description::String
fthandle::Ref{FT_HANDLE}
end
# D2XXDevice Constructors
#
"""
D2XXDevice(deviceidx::Integer)
Construct a `D2XXDevice` without opening it. D2XX hardware must pre present to
work.
"""
D2XXDevice(deviceidx::Integer) = D2XXDevice(getdeviceinfodetail(deviceidx)...)
"""
D2XXDevices()
Returns an array of available D2XX devices of type `D2XXDevice`.
Their state is not modified - if they are already open/closed they remain
open/closed.
See also: [`D2XXDevice`](@ref), [`open`](@ref)
"""
function D2XXDevices()
numdevs = createdeviceinfolist() # NB numdevs is DWORD = Cuint
devices = D2XXDevice[]
for devidx = 0:(Int(numdevs)-1) # Int conversion to avoid devidx = 0x00000000:0xffffffff on Win32
push!(devices, D2XXDevice(devidx))
end
devices
end
# Port communication functions
#
"""
isopen(d::D2XXDevice) -> Bool
See also: [`D2XXDevice`](@ref)
"""
Base.isopen(d::D2XXDevice) = isopen(fthandle(d))
"""
isopen(handle::FT_HANDLE) -> Bool
See also: [`FT_HANDLE`](@ref)
"""
function Base.isopen(handle::FT_HANDLE)
open = true
if Wrapper._ptr(handle) == C_NULL
open = false
else
try
FT_GetModemStatus(handle)
catch ex
if ex == FT_INVALID_HANDLE
open = false
else
rethrow(ex)
end
end
end
open
end
"""
Base.open(d::D2XXDevice)
Open a [`D2XXDevice`](@ref) for reading and writing using [`FT_OpenEx`](@ref).
Cannot be used to open the same device twice.
See also: [`isopen`](@ref), [`close`](@ref)
"""
function Base.open(d::D2XXDevice)
isopen(d) && throw(D2XXException("Device already open."))
fthandle(d, FT_Open(deviceidx(d)))
return
end
"""
open(str::AbstractString, openby::FTOpenBy) -> FT_HANDLE
Create an open [`FT_HANDLE`](@ref) for reading and writing using
[`FT_OpenEx`](@ref). Cannot be used to open the same device twice.
# Arguments
- `str::AbstractString` : Device identifier. Type depends on `openby`
- `openby::FTOpenBy` : Indicator of device identifier `str` type.
See also: [`isopen`](@ref), [`close`](@ref)
"""
Base.open(str::AbstractString, openby::FTOpenBy) = FT_OpenEx(str, DWORD(openby))
"""
close(d::D2XXDevice)
Close a [`D2XXDevice`](@ref) using [`FT_Close`](@ref). Does not perform a
[`flush`](@ref) first.
"""
Base.close(d::D2XXDevice) = close(fthandle(d))
"""
close(handle::FT_HANDLE)
Close an [`FT_HANDLE`](@ref) using [`FT_Close`](@ref). Does not perform a
[`flush`](@ref) first.
"""
function Base.close(handle::FT_HANDLE)
if isopen(handle)
FT_Close(handle)
end
return
end
"""
bytesavailable(d::D2XXDevice)
See also: [`D2XXDevice`](@ref), [`isopen`](@ref), [`open`](@ref),
[`readavailable`](@ref), [`read`](@ref)
"""
Base.bytesavailable(d::D2XXDevice) = bytesavailable(fthandle(d))
"""
bytesavailable(handle::FT_HANDLE)
See also: [`FT_HANDLE`](@ref), [`isopen`](@ref), [`open`](@ref),
[`readavailable`](@ref), [`read`](@ref)
"""
function Base.bytesavailable(handle::FT_HANDLE)
isopen(handle) || throw(D2XXException("Device must be open to check bytes available."))
FT_GetQueueStatus(handle)
end
"""
eof(d::D2XXDevice) -> Bool
Indicates if any bytes are available to be read from an open
[`D2XXDevice`](@ref). Non-blocking.
See also: [`isopen`](@ref), [`open`](@ref),
[`readavailable`](@ref), [`read`](@ref)
"""
Base.eof(d::D2XXDevice) = eof(fthandle(d))
"""
eof(d::D2XXDevice) -> Bool
Indicates if any bytes are available to be read from an open
[`FT_HANDLE`](@ref). Non-blocking.
See also: [`isopen`](@ref), [`open`](@ref),
[`readavailable`](@ref), [`read`](@ref)
"""
Base.eof(handle::FT_HANDLE) = (bytesavailable(handle) == 0)
"""
readbytes!(d::D2XXDevice, b::AbstractVector{UInt8}, nb=length(b))
See description for
[`readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))`](@ref).
`d` must be open. Uses [`FTRead`](@ref).
See also: [`D2XXDevice`](@ref).
"""
Base.readbytes!(d::D2XXDevice, b::AbstractVector{UInt8}, nb=length(b)) =
readbytes!(fthandle(d), b, nb)
"""
readbytes!(handle::FT_HANDLE, b::AbstractVector{UInt8}, nb=length(b))
See description for
[`readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))`](@ref).
`handle` must be open. Uses [`FTRead`](@ref).
See also: [`FT_HANDLE`](@ref)
"""
function Base.readbytes!(handle::FT_HANDLE, b::AbstractVector{UInt8}, nb=length(b))
isopen(handle) || throw(D2XXException("Device must be open to read."))
if length(b) < nb
resize!(b, nb)
end
nbrx = FT_Read(handle, b, nb)
end
"""
readavailable(d::D2XXDevice)
Read all available data from an open [`D2XXDevice`](@ref). Does not block if
nothing is available.
"""
Base.readavailable(d::D2XXDevice) = readavailable(fthandle(d))
"""
readavailable(handle::FT_HANDLE)
Read all available data from an open [`FT_HANDLE`](@ref). Does not block if
nothing is available.
See also: [`readbytes`](@ref) [`isopen`](@ref), [`open`](@ref)
"""
function Base.readavailable(handle::FT_HANDLE)
b = Vector{UInt8}(undef, bytesavailable(handle))
readbytes!(handle, b)
b
end
"""
write(d::D2XXDevice, buffer::Vector{UInt8})
Write `buffer` to an open [`D2XXDevice`](@ref) using [`FT_Write`](@ref).
"""
Base.write(d::D2XXDevice, buffer::Vector{UInt8}) = write(fthandle(d), buffer)
"""
write(handle::FT_HANDLE, buffer::Vector{UInt8})
Write `buffer` to an open [`FT_HANDLE`](@ref) using [`FT_Write`](@ref).
See also: [`isopen`](@ref), [`open`](@ref)
"""
function Base.write(handle::FT_HANDLE, buffer::Vector{UInt8})
isopen(handle) || throw(D2XXException("Device must be open to write."))
FT_Write(handle, buffer, length(buffer))
end
"""
baudrate(d::D2XXDevice, baud)
Set the baudrate of an open [`D2XXDevice`](@ref) using [`FT_SetBaudRate`](@ref).
"""
baudrate(d::D2XXDevice, baud) = baudrate(fthandle(d), baud)
"""
baudrate(handle::FT_HANDLE, baud)
Set the baudrate of an open [`FT_HANDLE`](@ref) to `baud` using
[`FT_SetBaudRate`](@ref).
See also: [`isopen`](@ref), [`open`](@ref)
"""
function baudrate(handle::FT_HANDLE, baud)
0 < baud || throw(DomainError("0 <= baud"))
isopen(handle) || throw(D2XXException("Device must be open to set baudrate."))
FT_SetBaudRate(handle, baud)
end
"""
datacharacteristics(d::D2XXDevice;
wordlength::FTWordLength = BITS_8,
stopbits::FTStopBits = STOP_BITS_1,
parity::FTParity = PARITY_NONE)
Set the transmission and reception data characteristics for an open
[`D2XXDevice`](@ref) using [`FT_SetDataCharacteristics`](@ref).
# Arguments
- `wordlength::FTWordLength` : Either BITS_7 or BITS_8
- `stopbits::FTStopBits` : Either STOP_BITS_1 or STOP_BITS_2
- `parity::FTParity` : PARITY_NONE, PARITY_ODD, PARITY_EVEN, PARITY_MARK, or
PARITY_SPACE
"""
datacharacteristics(d::D2XXDevice;
wordlength::FTWordLength = BITS_8,
stopbits::FTStopBits = STOP_BITS_1,
parity::FTParity = PARITY_NONE) =
datacharacteristics(fthandle(d),
wordlength=wordlength,
stopbits=stopbits,
parity=parity)
"""
datacharacteristics(handle::FT_HANDLE;
wordlength::FTWordLength = BITS_8,
stopbits::FTStopBits = STOP_BITS_1,
parity::FTParity = PARITY_NONE)
Set the transmission and reception data characteristics for an open
[`FT_HANDLE`](@ref) using [`FT_SetDataCharacteristics`](@ref).
See also: [`isopen`](@ref), [`open`](@ref)
"""
function datacharacteristics(handle::FT_HANDLE;
wordlength::FTWordLength = BITS_8,
stopbits::FTStopBits = STOP_BITS_1,
parity::FTParity = PARITY_NONE)
isopen(handle) || throw(D2XXException("Device must be open to set data characteristics."))
FT_SetDataCharacteristics(handle, DWORD(wordlength), DWORD(stopbits), DWORD(parity))
end
"""
timeouts(d::D2XXDevice, timeout_rd, timeout_wr)
Set the timeouts of an open [`D2XXDevice`](@ref) using [`FT_SetTimeouts`](@ref).
"""
timeouts(d::D2XXDevice, timeout_rd, timeout_wr) =
timeouts(fthandle(d) , timeout_rd, timeout_wr)
"""
timeouts(handle::FT_HANDLE, timeout_rd, timeout_wr)
Set the timeouts of an open [`FT_HANDLE`](@ref) using [`FT_SetTimeouts`](@ref).
Behaviour is undefined for `timeout_rd` = 0 and `timeout_wr` = 0.
`timeout_rd` = 0 appears to cause [`read`](@ref) and [`readavailable`](@ref) to
block.
See also: [`isopen`](@ref), [`open`](@ref)
"""
function timeouts(handle::FT_HANDLE, timeout_rd, timeout_wr)
0 <= timeout_rd || throw(DomainError("0 <= timeout_rd"))
0 <= timeout_wr || throw(DomainError("0 <= timeout_wr"))
isopen(handle) || throw(D2XXException("Device must be open to set timeouts."))
FT_SetTimeouts(handle, timeout_rd, timeout_wr)
end
"""
reset(d::D2XXDevice)
Reset an [`D2XXDevice`](@ref) using [`FT_ResetDevice`](@ref).
"""
resetdevice(d::D2XXDevice) = resetdevice(fthandle(d))
"""
reset(handle::FT_HANDLE)
Reset an [`FT_HANDLE`](@ref) using [`FT_ResetDevice`](@ref).
"""
function resetdevice(handle::FT_HANDLE)
if isopen(handle)
FT_ResetDevice(handle)
end
return
end
"""
usbparameters(d::D2XXDevice, transfersize_in, transfersize_out)
Set the USB input and output transfer buffer sizes in bytes, of an open [`D2XXDevice`](@ref).
Transfer sizes must be set to a multiple of 64 bytes between 64 bytes and 64k bytes.
`transfersize_in` and `transfersize_out` will be automatically rounded to the nearest
valid value. When usbparameters is called, the change comes into effect immediately
and any data that was held in the driver at the time of the change is lost.
Note that, at present, only transfersize_in is supported.
"""
usbparameters(d::D2XXDevice, transfersize_in, transfersize_out) =
usbparameters(fthandle(d), transfersize_in, transfersize_out)
"""
usbparameters(handle::FT_HANDLE, transfersize_in, transfersize_out)
Set the USB input and output transfer buffer sizes in bytes, of an open [`FT_HANDLE`](@ref).
Transfer sizes must be set to a multiple of 64 bytes between 64 bytes and 64k bytes.
`transfersize_in` and `transfersize_out` will be automatically rounded to the nearest
valid value. When `usbparameters` is called, the change comes into effect immediately
and any data that was held in the driver at the time of the change is lost.
Note that, at present, only transfersize_in is supported.
"""
function usbparameters(handle::FT_HANDLE, transfersize_in, transfersize_out)
isopen(handle) || throw(D2XXException("Device must be open to set USB parameters."))
transfersize_in = round(transfersize_in/64)*64
transfersize_out = round(transfersize_out/64)*64
64 <= transfersize_in || throw(DomainError("transfersize_in < 64"))
64 <= transfersize_out || throw(DomainError("transfersize_out < 64"))
65536 >= transfersize_in || throw(DomainError("transfersize_in > 65536"))
65536 >= transfersize_out || throw(DomainError("transfersize_out > 65536"))
FT_SetUSBParameters(handle, transfersize_in, transfersize_out)
end
"""
characters(d::D2XXDevice, transfersize_in, transfersize_out)
Set the event- and error characters of an open [`D2XXDevice`](@ref) using [`FT_SetChars`](@ref).
This function allows for inserting specified characters in the data stream to
represent events firing or errors occurring.
"""
characters(d::D2XXDevice, event_char, event_enable, error_char, error_enable) =
characters(fthandle(d), event_char, event_enable, error_char, error_enable)
"""
characters(handle::FT_HANDLE, transfersize_in, transfersize_out)
Set the event- and error characters of an open [`FT_HANDLE`](@ref) using [`FT_SetChars`](@ref).
This function allows for inserting specified characters in the data stream to
represent events firing or errors occurring.
"""
function characters(handle::FT_HANDLE, event_char, event_enable, error_char, error_enable)
isopen(handle) || throw(D2XXException("Device must be open to set event- and error characters."))
FT_SetChars(handle, UInt8(event_char), UInt8(event_enable), UInt8(error_char), UInt8(error_enable))
end
"""
latencytimer(d::D2XXDevice, timer_val)
Set the latency timer in milliseconds of an open [`D2XXDevice`](@ref) using [`FT_SetLatencyTimer`](@ref).
In the FT8U232AM and FT8U245AM devices, the receive buffer timeout that is used to flush
remaining data from the receive buffer was fixed at 16 ms. In all other FTDI devices, this
timeout is programmable and can be set in 1 ms intervals between 2ms and 255 ms.
This allows the device to be better optimized for protocols requiring faster response
times for short data packets.
"""
latencytimer(d::D2XXDevice, timer_val) = latencytimer(fthandle(d), timer_val)
"""
latencytimer(handle::FT_HANDLE, timer_val)
Set the latency timer in milliseconds of an open [`FT_HANDLE`](@ref) using [`FT_SetLatencyTimer`](@ref).
In the FT8U232AM and FT8U245AM devices, the receive buffer timeout that is used to flush
remaining data from the receive buffer was fixed at 16 ms. In all other FTDI devices, this
timeout is programmable and can be set in 1 ms intervals between 2ms and 255 ms.
This allows the device to be better optimized for protocols requiring faster response
times for short data packets.
"""
function latencytimer(handle::FT_HANDLE, timer_val)
isopen(handle) || throw(D2XXException("Device must be open to set latency timer."))
isinteger(timer_val) || throw(DomainError("latency timer value not an integer"))
2 <= timer_val || throw(DomainError("latency timer < 2"))
255 >= timer_val || throw(DomainError("latency timer > 255"))
FT_SetLatencyTimer(handle, UInt8(timer_val))
end
"""
latencytimer(d::D2XXDevice)
Return the latency timer in milliseconds of an open [`D2XXDevice`](@ref) using [`FT_GetLatencyTimer`](@ref).
"""
latencytimer(d::D2XXDevice) = latencytimer(fthandle(d))
"""
latencytimer(handle::FT_HANDLE)
Return the latency timer in milliseconds of an open [`FT_HANDLE`](@ref) using [`FT_GetLatencyTimer`](@ref).
"""
function latencytimer(handle::FT_HANDLE)
isopen(handle) || throw(D2XXException("Device must be open to get latency timer."))
return FT_GetLatencyTimer(handle)
end
"""
status(d::D2XXDevice) ->
mflaglist::Dict{String, Bool}, lflaglist::Dict{String, Bool}
Return `Bool` dictionaries of flags for the modem status (`mflaglist`) and
line status (`lflaglist`) for an open [`D2XXDevice`](@ref) using
[`FT_GetModemStatus`](@ref).
"""
status(d::D2XXDevice) = status(fthandle(d))
"""
status(d::D2XXDevice) ->
mflaglist::Dict{String, Bool}, lflaglist::Dict{String, Bool}
Return `Bool` dictionaries of flags for the modem status (`mflaglist`) and
line status (`lflaglist`) for an open [`FT_HANDLE`](@ref) using
[`FT_GetModemStatus`](@ref).
See also: [`isopen`](@ref), [`open`](@ref)
"""
function status(handle::FT_HANDLE)
isopen(handle) || throw(D2XXException("Device must be open to check status."))
flags = FT_GetModemStatus(handle)
modemstatus = flags & 0xFF
linestatus = (flags >> 8) & 0xFF
mflaglist = Dict{String, Bool}()
lflaglist = Dict{String, Bool}()
mflaglist["CTS"] = (modemstatus & 0x10) == 0x10
mflaglist["DSR"] = (modemstatus & 0x20) == 0x20
mflaglist["RI"] = (modemstatus & 0x40) == 0x40
mflaglist["DCD"] = (modemstatus & 0x80) == 0x89
# Below is only non-zero for windows
lflaglist["OE"] = (linestatus & 0x02) == 0x02
lflaglist["PE"] = (linestatus & 0x04) == 0x04
lflaglist["FE"] = (linestatus & 0x08) == 0x08
lflaglist["BI"] = (linestatus & 0x10) == 0x10
mflaglist, lflaglist
end
if Sys.iswindows()
"""
driverversion(d::D2XXDevice)
Get the driver version for an open [`D2XXDevice`](@ref) using
[`FT_GetDriverVersion`](@ref). Windows only.
"""
driverversion(d::D2XXDevice) = driverversion(fthandle(d))
"""
driverversion(handle::FT_HANDLE)
Get the driver version for an open [`FT_HANDLE`](@ref) using
[`FT_GetDriverVersion`](@ref). Windows only.
See also: [`isopen`](@ref), [`open`](@ref)
"""
function driverversion(handle::FT_HANDLE)
isopen(handle) || throw(D2XXException("Device must be open to check driver version"))
version = FT_GetDriverVersion(handle)
@assert (version >> 24) & 0xFF == 0x00 # 4th byte should be 0 according to docs
Util.versionnumber(version)
end
end # Sys.iswindows()
"""
bitmode(d::D2XXDevice, direction, mode::FTBitMode)
Set the initial pin direction and bit [`FTBitMode`](@ref) for an open [`D2XXDevice`](@ref).
"""
bitmode(d::D2XXDevice, direction, mode::FTBitMode) = bitmode(fthandle(d), direction, mode)
"""
bitmode(handle::FT_HANDLE, direction, mode::FTBitMode)
Set the initial pin direction and bit [`FTBitMode`](@ref) for an open [`D2XXDevice`](@ref).
"""
function bitmode(handle::FT_HANDLE, direction, mode::FTBitMode)
isopen(handle) || throw(D2XXException("Device must be open to set bit mode."))
FT_SetBitMode(handle, UInt8(direction), UInt8(mode))
return
end
"""
flush(d::D2XXDevice)
Clear the transmit and receive buffers for an open [`D2XXDevice`](@ref).
"""
Base.flush(d::D2XXDevice) = flush(fthandle(d))
"""
flush(handle::FT_HANDLE)
Clear the transmit and receive buffers for an open [`FT_HANDLE`](@ref).
See also: [`isopen`](@ref), [`open`](@ref), [`bytesavailable`](@ref)
"""
function Base.flush(handle::FT_HANDLE)
isopen(handle) || throw(D2XXException("Device must be open to flush."))
FT_StopInTask(handle)
FT_Purge(handle, FT_PURGE_TX|FT_PURGE_RX)
readavailable(handle)
FT_RestartInTask(handle)
end
# Other Functions
#
function createdeviceinfolist()
numdevs = FT_CreateDeviceInfoList()
end
function getdeviceinfodetail(deviceidx)
0 <= deviceidx || throw(DomainError("0 <= deviceidx"))
deviceidx < createdeviceinfolist() || throw(D2XXException("Device index $deviceidx not in range."))
idx, flags, typ, id, locid, serialnumber, description, fthandle = FT_GetDeviceInfoDetail(deviceidx)
end
# Library Functions
#
if Sys.iswindows()
"""
libversion()
Get a version number from a call to [`FT_GetLibraryVersion`](@ref). Windows
only.
"""
function libversion()
version = FT_GetLibraryVersion()
@assert (version >> 24) & 0xFF == 0x00 # 4th byte should be 0 according to docs
Util.versionnumber(version)
end
end # Sys.iswindows()
# D2XXDevice Accessor Functions
#
"""
deviceidx(d::D2XXDevice)
Get D2XXDevice index.
See also: [`D2XXDevice`](@ref)
"""
deviceidx(d::D2XXDevice) = d.idx
"""
deviceflags(d::D2XXDevice)
Get the D2XXDevice flags list.
See also: [`D2XXDevice`](@ref)
"""
deviceflags(d::D2XXDevice) = d.flags
"""
devicetype(d::D2XXDevice)
Get the D2XXDevice device type.
See also: [`D2XXDevice`](@ref)
"""
devicetype(d::D2XXDevice) = d.typ
"""
deviceid(d::D2XXDevice)
Get the D2XXDevice device id.
See also: [`D2XXDevice`](@ref)
"""
deviceid(d::D2XXDevice) = d.id
"""
locationid(d::D2XXDevice)
Get the D2XXDevice location id. This is zero for windows devices.
See also: [`D2XXDevice`](@ref)
"""
locationid(d::D2XXDevice) = d.locid
"""
serialnumber(d::D2XXDevice)
Get the D2XXDevice device serial number.
See also: [`D2XXDevice`](@ref)
"""
serialnumber(d::D2XXDevice) = d.serialnumber
"""
description(d::D2XXDevice)
Get the D2XXDevice device description.
See also: [`D2XXDevice`](@ref)
"""
description(d::D2XXDevice) = d.description
"""
fthandle(d::D2XXDevice)
Get the D2XXDevice device D2XX handle of type ::FT_HANDLE`.
See also: [`D2XXDevice`](@ref)
"""
fthandle(d::D2XXDevice) = d.fthandle[]
"""
fthandle(d::D2XXDevice, fthandle::FT_HANDLE)
Set the D2XXDevice device D2XX handle of type ::FT_HANDLE`.
See also: [`D2XXDevice`](@ref)
"""
fthandle(d::D2XXDevice, fthandle::FT_HANDLE) = (d.fthandle[] = fthandle)
end # module LibFTD2XX
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 1530 | # LibFTD2XX.jl - Utility Module
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
module Util
export ntuple2string, versionnumber
"""
function ntuple2string(input::NTuple{N, Cchar}) where N
Convert an NTuple of Cchars (optionally null terminated) to a julia string.
# Example
```jldoctest
julia> ntuple2string(Cchar.(('h','e','l','l','o')))
"hello"
julia> ntuple2string(Cchar.(('h','e','l','l','o', '\0', 'x'))) # null terminated
"hello"
```
"""
function ntuple2string(input::NTuple{N, Cchar}) where N
if any(input .== 0)
endidx = findall(input .== 0)[1]-1
elseif all(input .> 0)
endidx = N
else
throw(ArgumentError("No terminator or negative values!"))
end
String(UInt8.([char for char in input[1:endidx]]))
end
function versionnumber(hex)
hex <= 0x999999 || throw(DomainError("Input must be less than 0x999999"))
patchhex = UInt8( (hex & 0x0000FF) >> 0 )
patchhex <= 0x99 || throw(DomainError("Patch field must be less than or equal to 0x99"))
minorhex = UInt8( (hex & 0x00FF00) >> 8 )
minorhex <= 0x99 || throw(DomainError("Minor field must be less than or equal to 0x99"))
majorhex = UInt8( (hex & 0xFF0000) >> 16 )
majorhex <= 0x99 || throw(DomainError("Minor field must be less than or equal to 0x99"))
patchdec = 10(patchhex >> 4) + (patchhex & 0x0F)
minordec = 10(minorhex >> 4) + (minorhex & 0x0F)
majordec = 10(majorhex >> 4) + (majorhex & 0x0F)
VersionNumber(majordec,minordec,patchdec)
end
end # module Util | LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 33659 | # LibFTD2XX.jl - C Library Wrapper
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
#
# This module contains wrappers for D2XX devices. See D2XX Programmer's Guide
# (FT_000071) for more information. Function names match those in the library.
#
# Only recommended for advanced users. Note that there is minimal argument
# checking in these wrapper methods.
module Wrapper
# Type Aliases
export DWORD, ULONG, UCHAR
# Library Constants
export FT_OPEN_BY_SERIAL_NUMBER, FT_OPEN_BY_DESCRIPTION, FT_OPEN_BY_LOCATION
export FT_DEVICE
export FT_LIST_NUMBER_ONLY, FT_LIST_BY_INDEX, FT_LIST_ALL
export FT_BITS_8, FT_BITS_7
export FT_STOP_BITS_1, FT_STOP_BITS_2
export FT_PARITY_NONE, FT_PARITY_ODD, FT_PARITY_EVEN, FT_PARITY_MARK, FT_PARITY_SPACE
export FT_FLOW_NONE, FT_FLOW_RTS_CTS, FT_FLOW_DTR_DSR, FT_FLOW_XON_XOFF
export FT_EVENT_RXCHAR, FT_EVENT_MODEM_STATUS, FT_EVENT_LINE_STATUS
export FT_PURGE_RX, FT_PURGE_TX
export FT_MODE_RESET,
FT_MODE_ASYNC_BITBANG,
FT_MODE_MPSSE,
FT_MODE_SYNC_BITBANG,
FT_MODE_MCU_EMULATION,
FT_MODE_FAST_OPTO,
FT_MODE_CBUS_BITBANG,
FT_MODE_SCS_FIFO
export FT_STATUS_ENUM,
FT_OK,
FT_INVALID_HANDLE,
FT_DEVICE_NOT_FOUND,
FT_DEVICE_NOT_OPENED,
FT_IO_ERROR,
FT_INSUFFICIENT_RESOURCES,
FT_INVALID_PARAMETER,
FT_INVALID_BAUD_RATE,
FT_DEVICE_NOT_OPENED_FOR_ERASE,
FT_DEVICE_NOT_OPENED_FOR_WRITE,
FT_FAILED_TO_WRITE_DEVICE,
FT_EEPROM_READ_FAILED,
FT_EEPROM_WRITE_FAILED,
FT_EEPROM_ERASE_FAILED,
FT_EEPROM_NOT_PRESENT,
FT_EEPROM_NOT_PROGRAMMED,
FT_INVALID_ARGS,
FT_NOT_SUPPORTED,
FT_OTHER_ERROR,
FT_DEVICE_LIST_NOT_READY
# Types
export FT_HANDLE
# Functions
export FT_CreateDeviceInfoList,
FT_GetDeviceInfoList,
FT_GetDeviceInfoDetail,
FT_ListDevices,
FT_Open,
FT_OpenEx,
FT_Close,
FT_Read,
FT_Write,
FT_SetBaudRate,
FT_SetDataCharacteristics,
FT_SetTimeouts,
FT_SetFlowControl,
FT_SetDtr,
FT_ClrDtr,
FT_SetRts,
FT_ClrRts,
FT_GetModemStatus,
FT_GetQueueStatus,
FT_GetDeviceInfo,
FT_GetDriverVersion,
FT_GetLibraryVersion,
FT_GetStatus,
FT_SetEventNotification,
FT_SetChars,
FT_SetBreakOn,
FT_SetBreakOff,
FT_Purge,
FT_ResetDevice,
FT_StopInTask,
FT_RestartInTask,
FT_GetLatencyTimer,
FT_SetLatencyTimer,
FT_SetBitMode,
FT_GetBitMode,
FT_SetUSBParameters
using Libdl
using libftd2xx_jll
# Type Aliases
#
const DWORD = UInt32
const ULONG = UInt64
const USHORT = UInt16
const UCHAR = UInt8
const FT_STATUS = DWORD
# Library Constants
#
# FT_OpenEx Flags
const FT_OPEN_BY_SERIAL_NUMBER = 1
const FT_OPEN_BY_DESCRIPTION = 2
const FT_OPEN_BY_LOCATION = 4
# FT_GetDeviceInfo FT_DEVICE Type Enum
@enum(
FT_DEVICE,
FT_DEVICE_232BM = DWORD(0),
FT_DEVICE_232AM = DWORD(1),
FT_DEVICE_100AX = DWORD(2),
FT_DEVICE_UNKNOWN = DWORD(3),
FT_DEVICE_2232C = DWORD(4),
FT_DEVICE_232R = DWORD(5),
FT_DEVICE_2232H = DWORD(6),
FT_DEVICE_4232H = DWORD(7),
FT_DEVICE_232H = DWORD(8),
FT_DEVICE_X_SERIES = DWORD(9)
)
# FT_ListDevices Flags (used in conjunction with FT_OpenEx Flags)
const FT_LIST_NUMBER_ONLY = 0x80000000
const FT_LIST_BY_INDEX = 0x40000000
const FT_LIST_ALL = 0x20000000
# Word Lengths
const FT_BITS_8 = 8
const FT_BITS_7 = 7
# Stop Bits
const FT_STOP_BITS_1 = 0
const FT_STOP_BITS_2 = 2
# Parity
const FT_PARITY_NONE = 0
const FT_PARITY_ODD = 1
const FT_PARITY_EVEN = 2
const FT_PARITY_MARK = 3
const FT_PARITY_SPACE = 4
# FT_SetFlowControl Flow Control Flags
const FT_FLOW_NONE = 0x0000
const FT_FLOW_RTS_CTS = 0x0100
const FT_FLOW_DTR_DSR = 0x0200
const FT_FLOW_XON_XOFF = 0x0400
# FT_SetEventNotification Event Flags (not yet implemented)
const FT_EVENT_RXCHAR = 1
const FT_EVENT_MODEM_STATUS = 2
const FT_EVENT_LINE_STATUS = 4
# FT_Purge Flags
const FT_PURGE_RX = 1
const FT_PURGE_TX = 2
# Mode Flags
const FT_MODE_RESET = 0x00
const FT_MODE_ASYNC_BITBANG = 0x01
const FT_MODE_MPSSE = 0x02
const FT_MODE_SYNC_BITBANG = 0x04
const FT_MODE_MCU_EMULATION = 0x08
const FT_MODE_FAST_OPTO = 0x10
const FT_MODE_CBUS_BITBANG = 0x20
const FT_MODE_SCS_FIFO = 0x40
# FT_STATUS Return Values
@enum(
FT_STATUS_ENUM,
FT_OK,
FT_INVALID_HANDLE,
FT_DEVICE_NOT_FOUND,
FT_DEVICE_NOT_OPENED,
FT_IO_ERROR,
FT_INSUFFICIENT_RESOURCES,
FT_INVALID_PARAMETER,
FT_INVALID_BAUD_RATE,
FT_DEVICE_NOT_OPENED_FOR_ERASE,
FT_DEVICE_NOT_OPENED_FOR_WRITE,
FT_FAILED_TO_WRITE_DEVICE,
FT_EEPROM_READ_FAILED,
FT_EEPROM_WRITE_FAILED,
FT_EEPROM_ERASE_FAILED,
FT_EEPROM_NOT_PRESENT,
FT_EEPROM_NOT_PROGRAMMED,
FT_INVALID_ARGS,
FT_NOT_SUPPORTED,
FT_OTHER_ERROR,
FT_DEVICE_LIST_NOT_READY)
# Types
#
"""
struct FT_DEVICE_LIST_INFO_NODE
Julia language representation of the `FT_DEVICE_LIST_INFO_NODE` structure which
is passed to `FT_GetDeviceInfoList`.
Pre-allocated arrays of `Cchar` (in julia, represented as `NTuple{L, Cchar}`)
are filled by `FT_GetDeviceInfoList` with null terminated strings. They can be
converted to julia strings using [`ntuple2string`](@ref).
"""
struct FT_DEVICE_LIST_INFO_NODE
flags::DWORD
typ::DWORD
id::DWORD
locid::DWORD
serialnumber::NTuple{16, Cchar}
description::NTuple{64, Cchar}
fthandle_ptr::Ptr{Cvoid}
end
"""
mutable struct FT_HANDLE <: IO
Holds a handle to an FT D2XX device.
"""
mutable struct FT_HANDLE <: IO
p::Ptr{Cvoid}
end
"""
FT_HANDLE()
Constructs a handle to an FT D2XX device that points to `C_NULL`. Initialsed
with a finalizer that calls [`destroy!`](@ref).
"""
function FT_HANDLE()
handle = FT_HANDLE(C_NULL)
finalizer(destroy!, handle)
handle
end
"""
destroy!(handle::FT_HANDLE)
Destructor for the [`FT_HANDLE`](@ref) type.
"""
function destroy!(handle::FT_HANDLE)
if _ptr(handle) != C_NULL
FT_Close(handle)
end
end
## Type Accessors
#
"""
_ptr(handle::FT_HANDLE)
Get the raw pointer for an [`FT_HANDLE`](@ref).
"""
_ptr(handle::FT_HANDLE) = handle.p
"""
_ptr(handle::FT_HANDLE, fthandle_ptr::Ptr{Cvoid})
Set the raw pointer for an [`FT_HANDLE`](@ref).
"""
_ptr(handle::FT_HANDLE, fthandle_ptr::Ptr{Cvoid}) = (handle.p = fthandle_ptr)
# Utility functions
#
# Internal use only
function check(status::FT_STATUS)
FT_STATUS_ENUM(status) == FT_OK || throw(FT_STATUS_ENUM(status))
end
# wrapper functions
#
"""
FT_CreateDeviceInfoList()
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> "Number of devices is \$numdevs"
"Number of devices is 4"
```
"""
function FT_CreateDeviceInfoList()
lpdwNumDevs = Ref{DWORD}(0)
status = ccall((:FT_CreateDeviceInfoList, libftd2xx), cdecl, FT_STATUS,
(Ref{DWORD},),
lpdwNumDevs)
check(status)
lpdwNumDevs[]
end
"""
FT_GetDeviceInfoList(lpdwNumDevs)
# Arguments
- `lpdwNumDevs`: The number of devices.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> devinfolist, numdevs = FT_GetDeviceInfoList(numdevs);
julia> numdevs
0x00000004
julia> using LibFTD2XX.Util # for ntuple2string
julia> ntuple2string(devinfolist[1].description)
"USB <-> Serial Converter D"
julia> devinfolist[1].fthandle_ptr
Ptr{Nothing} @0x0000000000000000
julia> devinfolist[1].locid
0x00000000
julia> devinfolist[1].typ
0x00000007
julia> devinfolist[1].flags
0x00000002
julia> devinfolist[1].id
0x04036011
julia> ntuple2string(devinfolist[1].serialnumber)
"FT3AD2HCD"
```
"""
function FT_GetDeviceInfoList(lpdwNumDevs)
pDest = Vector{FT_DEVICE_LIST_INFO_NODE}(undef, lpdwNumDevs)
status = ccall((:FT_GetDeviceInfoList, libftd2xx), cdecl, FT_STATUS,
(Ref{FT_DEVICE_LIST_INFO_NODE}, Ref{DWORD}),
pDest, Ref{DWORD}(lpdwNumDevs))
check(status)
pDest, lpdwNumDevs
end
"""
FT_GetDeviceInfoDetail(dwIndex)
# Arguments
- `dwIndex`: Index of entry in the device info list.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> idx, flags, typ, id, locid, serialnumber, description, fthandle = FT_GetDeviceInfoDetail(0) # zero indexed
(0, 0x00000002, 0x00000007, 0x04036011, 0x00000000, "FT3AD2HCD", "USB <-> Serial Converter D", FT_HANDLE(Ptr{Nothing} @0x0000000000000000))
```
"""
function FT_GetDeviceInfoDetail(dwIndex)
lpdwFlags, lpdwType = Ref{DWORD}(), Ref{DWORD}()
lpdwID, lpdwLocId = Ref{DWORD}(), Ref{DWORD}()
pcSerialNumber = pointer(Vector{Cchar}(undef, 16))
pcDescription = pointer(Vector{Cchar}(undef, 64))
ftHandle = FT_HANDLE()
status = ccall((:FT_GetDeviceInfoDetail, libftd2xx), cdecl, FT_STATUS,
(DWORD, Ref{DWORD}, Ref{DWORD}, Ref{DWORD}, Ref{DWORD}, Cstring, Cstring, Ref{FT_HANDLE}),
dwIndex, lpdwFlags, lpdwType, lpdwID, lpdwLocId, pcSerialNumber, pcDescription, ftHandle)
check(status)
dwIndex[], lpdwFlags[], lpdwType[], lpdwID[], lpdwLocId[], unsafe_string(pcSerialNumber), unsafe_string(pcDescription), ftHandle
end
"""
FT_ListDevices(pvArg1, pvArg2, dwFlags)
**NOT FULLY FUNCTIONAL: NOT RECOMMENDED FOR USE**.
# Arguments
- `pvArg1`: Depends on dwFlags.
- `pvArg2`: Depends on dwFlags.
- `dwFlags`: Flag which determines format of returned information.
E.g. call with `pvArg1 = Ref{UInt32}()` and/or `pvArg2 = Ref{UInt32}()` for
cases where `pvArg1` and/or `pvArg2` return or are given DWORD information.
# Examples
1. Get number of devices...
```julia-repl
julia> numdevs = Ref{UInt32}();
julia> FT_ListDevices(numdevs, Ref{UInt32}(), FT_LIST_NUMBER_ONLY)
julia> numdevs[]
0x00000004
```
2. Get serial number of first device... *NOT CURRENTLY WORKING*
```julia-repl
julia> devidx = Ref{UInt32}(0)
Base.RefValue{UInt32}(0x00000000)
julia> buffer = pointer(Vector{Cchar}(undef, 64))
Ptr{Int8} @0x0000000004f2e530
julia> FT_ListDevices(devidx, buffer, FT_LIST_BY_INDEX|FT_OPEN_BY_SERIAL_NUMBER)
ERROR: FT_ListDevices wrapper does not yet flags other than FT_LIST_NUMBER_ONLY.
Stacktrace:
...
```
"""
function FT_ListDevices(pvArg1, pvArg2, dwFlags)
dwFlags == FT_LIST_NUMBER_ONLY || throw(ErrorException("FT_ListDevices wrapper does not yet flags other than FT_LIST_NUMBER_ONLY."))
flagsarg = DWORD(dwFlags)
status = ccall((:FT_ListDevices, libftd2xx), cdecl, FT_STATUS,
(Ptr{Cvoid}, Ptr{Cvoid}, DWORD),
pvArg1, pvArg2, dwFlags)
check(status)
return
end
"""
FT_Open(iDevice)
# Arguments
- `iDevice`: Zero-base index of device to open
# Example
```julia-repl
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000000c4970)
```
"""
function FT_Open(iDevice)
ftHandle = FT_HANDLE()
status = ccall((:FT_Open, libftd2xx), cdecl, FT_STATUS, (Int, Ref{FT_HANDLE}),
iDevice, ftHandle)
if FT_STATUS_ENUM(status) != FT_OK
_ptr(ftHandle, C_NULL)
throw(FT_STATUS_ENUM(status))
end
ftHandle
end
"""
FT_OpenEx(pvArg1::AbstractString, dwFlags::Integer)
# Arguments
- `pvArg1::AbstractString` : Either description or serial number depending on
`dwFlags`.
- `dwFlags::Integer` : FT_OPEN_BY_DESCRIPTION or FT_OPEN_BY_SERIAL_NUMBER.
Note that FT_OPEN_BY_LOCATION is not currently supported.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> idx, flags, typ, id, locid, serialnumber, description, fthandle = FT_GetDeviceInfoDetail(0)
(0, 0x00000002, 0x00000007, 0x04036011, 0x00000000, "FT3AD2HCD", "USB <-> Serial Converter D", FT_HANDLE(Ptr{Nothing} @0x0000000000000000))
julia> handle = FT_OpenEx(description, FT_OPEN_BY_DESCRIPTION)
FT_HANDLE(Ptr{Nothing} @0x0000000000dfe740)
julia> isopen(handle)
true
julia> close(handle)
julia> handle = FT_OpenEx(serialnumber, FT_OPEN_BY_SERIAL_NUMBER)
FT_HANDLE(Ptr{Nothing} @0x0000000005448ea0)
julia> isopen(handle)
true
julia> close(handle)
```
"""
function FT_OpenEx(pvArg1::AbstractString, dwFlags::Integer)
@assert (dwFlags == FT_OPEN_BY_DESCRIPTION) | (dwFlags == FT_OPEN_BY_SERIAL_NUMBER)
flagsarg = DWORD(dwFlags)
handle = FT_HANDLE()
status = ccall((:FT_OpenEx, libftd2xx), cdecl, FT_STATUS,
(Cstring , DWORD, Ref{FT_HANDLE}),
pvArg1, flagsarg, handle)
if FT_STATUS_ENUM(status) != FT_OK
_ptr(handle, C_NULL)
throw(FT_STATUS_ENUM(status))
end
handle
end
"""
FT_Close(ftHandle::FT_HANDLE)
Closes an open device and sets the pointer to C_NULL.
# Example
```julia-repl
julia> julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x000000000010a870)
julia> FT_Close(handle)
```
"""
function FT_Close(ftHandle::FT_HANDLE)
status = ccall((:FT_Close, libftd2xx), cdecl, FT_STATUS, (FT_HANDLE, ),
ftHandle)
check(status)
_ptr(ftHandle, C_NULL)
return
end
"""
FT_Read(ftHandle::FT_HANDLE, lpBuffer::AbstractVector{UInt8}, dwBytesToRead::Integer)
Returns number of bytes read.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> buffer = zeros(UInt8, 2)
2-element Array{UInt8,1}:
0x00
0x00
julia> nread = FT_Read(handle, buffer, 0) # read 0 bytes. Returns number read...
0x00000000
julia> buffer # should be unmodified...
2-element Array{UInt8,1}:
0x00
0x00
julia> FT_Close(handle)
```
"""
function FT_Read(ftHandle::FT_HANDLE, lpBuffer::AbstractVector{UInt8}, dwBytesToRead::Integer)
@assert 0 <= dwBytesToRead <= length(lpBuffer)
lpdwBytesReturned = Ref{DWORD}()
status = ccall((:FT_Read, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{UInt8}, DWORD, Ref{DWORD}),
ftHandle, lpBuffer, dwBytesToRead, lpdwBytesReturned)
check(status)
lpdwBytesReturned[]
end
"""
FT_Write(ftHandle::FT_HANDLE, lpBuffer::Vector{UInt8}, dwBytesToWrite::Integer)
Returns number of bytes written.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> buffer = ones(UInt8, 2)
2-element Array{UInt8,1}:
0x01
0x01
julia> nwr = FT_Write(handle, buffer, 0) # Write 0 bytes...
0x00000000
julia> buffer # should be unmodified...
2-element Array{UInt8,1}:
0x01
0x01
julia> nwr = FT_Write(handle, buffer, 2) # Write 2 bytes...
0x00000002
julia> buffer # should be unmodified...
2-element Array{UInt8,1}:
0x01
0x01
julia> FT_Close(handle)
```
"""
function FT_Write(ftHandle::FT_HANDLE, lpBuffer::AbstractVector{UInt8}, dwBytesToWrite::Integer)
@assert 0 <= dwBytesToWrite <= length(lpBuffer)
lpdwBytesWritten = Ref{DWORD}()
status = ccall((:FT_Write, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{UInt8}, DWORD, Ref{DWORD}),
ftHandle, lpBuffer, dwBytesToWrite, lpdwBytesWritten)
check(status)
lpdwBytesWritten[]
end
"""
FT_SetBaudRate(ftHandle::FT_HANDLE, dwBaudRate::Integer)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetBaudRate(handle, 115200) # Set baud rate to 115200
julia> FT_Close(handle)
```
"""
function FT_SetBaudRate(ftHandle::FT_HANDLE, dwBaudRate::Integer)
@assert 0 < dwBaudRate <= typemax(DWORD)
status = ccall((:FT_SetBaudRate, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, DWORD),
ftHandle, dwBaudRate)
check(status)
return
end
"""
FT_SetDataCharacteristics(ftHandle::FT_HANDLE, uWordLength, uStopBits, uParity)
# Arguments
- `ftHandle` : device handle
- `uWordLength` : Bits per word - either FT_BITS_8 or FT_BITS_7
- `uStopBits` : Stop bits - either FT_STOP_BITS_1 or FT_STOP_BITS_2
- `uParity` : Parity - either FT_PARITY_EVEN, FT_PARITY_ODD, FT_PARITY_MARK,
FT_PARITY_SPACE, or FT_PARITY_NONE.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)
julia> FT_Close(handle)
```
"""
function FT_SetDataCharacteristics(ftHandle::FT_HANDLE, uWordLength, uStopBits, uParity)
@assert (uWordLength == FT_BITS_8) || (uWordLength == FT_BITS_7)
@assert (uStopBits == FT_STOP_BITS_1) || (uStopBits == FT_STOP_BITS_2)
@assert (uParity == FT_PARITY_EVEN) || (uParity == FT_PARITY_ODD) ||
(uParity == FT_PARITY_MARK) || (uParity == FT_PARITY_SPACE) ||
(uParity == FT_PARITY_NONE)
status = ccall((:FT_SetDataCharacteristics, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, UCHAR, UCHAR, UCHAR),
ftHandle, uWordLength, uStopBits, uParity)
check(status)
return
end
"""
FT_SetTimeouts(ftHandle::FT_HANDLE, dwReadTimeout, dwWriteTimeout)
# Arguments
- `ftHandle` : device handle
- `dwReadTimeout` : Read timeout (milliseconds)
- `dwWriteTimeout` : Write timeout (milliseconds)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetBaudRate(handle, 9600)
julia> FT_SetTimeouts(handle, 50, 10) # 50ms read timeout, 10 ms write timeout
julia> buffer = zeros(UInt8, 5000);
julia> @time nwr = FT_Write(handle, buffer, 5000) # writes nothing if timesout
0.014323 seconds (4 allocations: 160 bytes)
0x00000000
julia> @time nread = FT_Read(handle, buffer, 5000)
0.049545 seconds (4 allocations: 160 bytes)
0x00000000
julia> FT_Close(handle)
```
"""
function FT_SetTimeouts(ftHandle::FT_HANDLE, dwReadTimeout, dwWriteTimeout)
status = ccall((:FT_SetTimeouts, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, DWORD, DWORD,),
ftHandle, dwReadTimeout, dwWriteTimeout)
check(status)
return
end
"""
FT_SetFlowControl(ftHandle::FT_HANDLE, usFlowControl, uXon, uXoff)
# Arguments
- `ftHandle` : device handle
- `usFlowControl` :
- `uXon` :
- `uXoff` :
# Example
"""
function FT_SetFlowControl(ftHandle::FT_HANDLE, usFlowControl, uXon, uXoff)
@assert usFlowControl in (FT_FLOW_NONE,FT_FLOW_RTS_CTS,FT_FLOW_DTR_DSR,FT_FLOW_XON_XOFF)
status = ccall((:FT_SetFlowControl, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, USHORT, UCHAR, UCHAR,),
ftHandle, usFlowControl, uXon, uXoff)
check(status)
return
end
"""
FT_SetDtr(ftHandle::FT_HANDLE)
# Example
"""
function FT_SetDtr(ftHandle::FT_HANDLE)
status = ccall((:FT_SetDtr, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE,),
ftHandle,)
check(status)
return
end
"""
FT_ClrDtr(ftHandle::FT_HANDLE)
# Example
"""
function FT_ClrDtr(ftHandle::FT_HANDLE)
status = ccall((:FT_ClrDtr, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE,),
ftHandle,)
check(status)
return
end
"""
FT_SetRts(ftHandle::FT_HANDLE)
# Example
"""
function FT_SetRts(ftHandle::FT_HANDLE)
status = ccall((:FT_SetRts, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE,),
ftHandle,)
check(status)
return
end
"""
FT_ClrRts(ftHandle::FT_HANDLE)
# Example
"""
function FT_ClrRts(ftHandle::FT_HANDLE)
status = ccall((:FT_ClrRts, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE,),
ftHandle,)
check(status)
return
end
"""
FT_GetModemStatus(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> flags = FT_GetModemStatus(handle)
0x00006400
julia> FT_Close(handle)
```
"""
function FT_GetModemStatus(ftHandle::FT_HANDLE)
lpdwModemStatus = Ref{DWORD}()
status = ccall((:FT_GetModemStatus, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{DWORD}),
ftHandle, lpdwModemStatus)
check(status)
lpdwModemStatus[]
end
"""
FT_GetQueueStatus(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> nbrx = FT_GetQueueStatus(handle) # get number of items in recieve queue
0x00000000
julia> FT_Close(handle)
```
"""
function FT_GetQueueStatus(ftHandle::FT_HANDLE)
lpdwAmountInRxQueue = Ref{DWORD}()
status = ccall((:FT_GetQueueStatus, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{DWORD}),
ftHandle, lpdwAmountInRxQueue)
check(status)
lpdwAmountInRxQueue[]
end
"""
FT_GetDeviceInfo(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> typ, id, serialnumber, description = FT_GetDeviceInfo(handle);
julia> FT_Close(handle)
```
"""
function FT_GetDeviceInfo(ftHandle::FT_HANDLE)
pftType = Ref{FT_DEVICE}()
lpdwID = Ref{DWORD}()
pcSerialNumber = pointer(Vector{Cchar}(undef, 16))
pcDescription = pointer(Vector{Cchar}(undef, 64))
pvDummy = C_NULL
status = ccall((:FT_GetDeviceInfo, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{FT_DEVICE}, Ref{DWORD}, Cstring, Cstring, Ptr{Cvoid}),
ftHandle, pftType, lpdwID, pcSerialNumber, pcDescription, pvDummy)
check(status)
pftType[], lpdwID[], unsafe_string(pcSerialNumber), unsafe_string(pcDescription)
end
if Sys.iswindows()
"""
FT_GetDriverVersion(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> version = FT_GetDriverVersion(handle)
0x00021212
julia> patch = version & 0xFF
0x00000012
julia> minor = (version >> 8) & 0xFF
0x00000012
julia> major = (version >> 16) & 0xFF
0x00000002
julia> VersionNumber(major,minor,patch)
v"2.18.18"
julia> FT_Close(handle)
```
"""
function FT_GetDriverVersion(ftHandle::FT_HANDLE)
lpdwDriverVersion = Ref{DWORD}()
status = ccall((:FT_GetDriverVersion, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{DWORD}),
ftHandle, lpdwDriverVersion)
check(status)
lpdwDriverVersion[]
end
"""
FT_GetLibraryVersion()
# Example
```julia-repl
julia> version = FT_GetLibraryVersion()
0x00021212
julia> patch = version & 0xFF
0x00000012
julia> minor = (version >> 8) & 0xFF
0x00000012
julia> major = (version >> 16) & 0xFF
0x00000002
julia> VersionNumber(major,minor,patch)
v"2.18.18"
```
"""
function FT_GetLibraryVersion()
lpdwDLLVersion = Ref{DWORD}()
status = ccall((:FT_GetLibraryVersion, libftd2xx), cdecl, FT_STATUS,
(Ref{DWORD},),
lpdwDLLVersion)
check(status)
version = lpdwDLLVersion[]
end
end # Sys.iswindows()
"""
FT_GetStatus(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> nbrx, nbtx, eventstatus = FT_GetStatus(handle)
(0x00000000, 0x00000000, 0x00000000)
julia> FT_Close(handle)
```
"""
function FT_GetStatus(ftHandle::FT_HANDLE)
lpdwAmountInRxQueue, lpdwAmountInTxQueue = Ref{DWORD}(), Ref{DWORD}()
lpdwEventStatus = Ref{DWORD}()
status = ccall((:FT_GetStatus, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{DWORD}, Ref{DWORD}, Ref{DWORD}),
ftHandle, lpdwAmountInRxQueue, lpdwAmountInTxQueue, lpdwEventStatus)
check(status)
lpdwAmountInRxQueue[], lpdwAmountInTxQueue[], lpdwEventStatus[]
end
"""
FT_SetEventNotification(ftHandle::FT_HANDLE, dwEventMask, pvArg)
Sets conditions for event notification.
An application can use this function to setup conditions which allow a thread to block
until one of the conditions is met. Typically, an application will create an event,
call this function, then block on the event. When the conditions are met, the event is set,
and the application thread unblocked. `dwEventMask` is a bit-map that describes the events
the application is interested in. `pvArg` is interpreted as the handle of an event which
has been created by the application. If one of the event conditions is met, the event is
set. If `dwEventMask=FT_EVENT_RXCHAR`, the event will be set when a character has been
received by the device. If `dwEventMask=FT_EVENT_MODEM_STATUS`, the event will be set when
a change in the modem signals has been detected by the device.
If `dwEventMask=FT_EVENT_LINE_STATUS`, the event will be set when a change in the line
status has been detected by the device.
"""
function FT_SetEventNotification(ftHandle::FT_HANDLE, dwEventMask, pvArg)
@assert dwEventMask in (FT_EVENT_RXCHAR,FT_EVENT_MODEM_STATUS,FT_EVENT_LINE_STATUS)
status = ccall((:FT_SetEventNotification, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, DWORD, Ptr{Cvoid}),
ftHandle, dwEventMask, pvArg)
check(status)
return
end
"""
FT_SetChars(ftHandle::FT_HANDLE, uEventCh, uEventChEn, uErrorCh, uErrorChEn)
This function sets the special characters for the device.
This function allows for inserting specified characters in the data stream to represent
events firing or errors occurring.
"""
function FT_SetChars(ftHandle::FT_HANDLE, uEventCh, uEventChEn, uErrorCh, uErrorChEn)
status = ccall((:FT_SetChars, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, UCHAR, UCHAR, UCHAR, UCHAR,),
ftHandle, uEventCh, uEventChEn, uErrorCh, uErrorChEn)
check(status)
return
end
"""
FT_SetBreakOn(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetBreakOn(handle) # break now on...
julia> FT_Close(handle)
```
"""
function FT_SetBreakOn(ftHandle::FT_HANDLE)
status = ccall((:FT_SetBreakOn, libftd2xx), cdecl, FT_STATUS, (FT_HANDLE,),
ftHandle)
check(status)
return
end
"""
FT_SetBreakOff(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetBreakOff(handle) # break now off...
julia> FT_Close(handle)
```
"""
function FT_SetBreakOff(ftHandle::FT_HANDLE)
status = ccall((:FT_SetBreakOff, libftd2xx), cdecl, FT_STATUS, (FT_HANDLE,),
ftHandle)
check(status)
return
end
"""
FT_Purge(ftHandle::FT_HANDLE, dwMask)
# Arguments
- `ftHandle::FT_HANDLE` : handle to open device
- `dwMask` : must be `FT_PURGE_RX`, `FT_PURGE_TX` or
`FT_PURGE_TX | FT_PURGE_RX`.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_Purge(handle, FT_PURGE_RX|FT_PURGE_TX)
julia> nbrx, nbtx, eventstatus = FT_GetStatus(handle) # All queues empty!
(0x00000000, 0x00000000, 0x00000000)
julia> FT_Close(handle)
```
"""
function FT_Purge(ftHandle::FT_HANDLE, dwMask)
@assert (dwMask == FT_PURGE_RX) || (dwMask == FT_PURGE_TX) ||
(dwMask == FT_PURGE_RX|FT_PURGE_TX)
status = ccall((:FT_SetBreakOff, libftd2xx), cdecl, FT_STATUS, (FT_HANDLE, DWORD),
ftHandle, dwMask)
check(status)
return
end
"""
FT_ResetDevice(ftHandle::FT_HANDLE)
Send a reset command to the device.
# Example
"""
function FT_ResetDevice(ftHandle::FT_HANDLE)
status = ccall((:FT_ResetDevice, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE,),
ftHandle)
check(status)
return
end
"""
FT_StopInTask(ftHandle::FT_HANDLE)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_StopInTask(handle) # The driver's IN task is now stopped.
julia> FT_RestartInTask(handle) # The driver's IN task is now restarted.
julia> FT_Close(handle)
```
"""
function FT_StopInTask(ftHandle::FT_HANDLE)
status = ccall((:FT_StopInTask, libftd2xx), cdecl, FT_STATUS, (FT_HANDLE,),
ftHandle)
check(status)
return
end
"""
FT_RestartInTask(ftHandle::FT_HANDLE)
# Example
See `FT_StopInTask`.
"""
function FT_RestartInTask(ftHandle::FT_HANDLE)
status = ccall((:FT_RestartInTask, libftd2xx), cdecl, FT_STATUS, (FT_HANDLE,),
ftHandle)
check(status)
return
end
"""
FT_GetLatencyTimer(ftHandle::FT_HANDLE)
Get the current latency timer in milliseconds.
# Example
See `FT_GetLatencyTimer`.
"""
function FT_GetLatencyTimer(ftHandle::FT_HANDLE)
pucTimer = Ref{UCHAR}()
status = ccall((:FT_GetLatencyTimer, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{UCHAR}),
ftHandle, pucTimer)
check(status)
pucTimer[]
end
"""
FT_SetLatencyTimer(ftHandle::FT_HANDLE, ucTimer)
Get the current latency timer value in milliseconds.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetLatencyTimer(handle, 0x0A)
julia> FT_GetLatencyTimer(handle)
0x0a
See `FT_GetLatencyTimer`.
"""
function FT_SetLatencyTimer(ftHandle::FT_HANDLE, ucTimer)
status = ccall((:FT_SetLatencyTimer, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, UCHAR),
ftHandle, ucTimer)
check(status)
return
end
"""
FT_GetBitMode(ftHandle::FT_HANDLE)
Get the current bit mode.
# Example
See `FT_SetBitMode`.
"""
function FT_GetBitMode(ftHandle::FT_HANDLE)
pucMode = Ref{UCHAR}()
status = ccall((:FT_GetBitMode, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, Ref{UCHAR}),
ftHandle, pucMode)
check(status)
pucMode[]
end
"""
FT_SetBitMode(ftHandle::FT_HANDLE, ucMask, ucMode)
Enables different chip modes.
`ucMask` sets up which bits are inputs and outputs. A bit value of 0 sets the corresponding
pin to an input, a bit value of 1 sets the corresponding pin to an output. In the case of
CBUS Bit Bang, the upper nibble of this value controls which pins are inputs and outputs,
while the lower nibble controls which of the outputs are high and low.
`ucModeMode` sets the chip mode, and must be one of the following:
0x0 = Reset
0x1 = Asynchronous Bit Bang
0x2 = MPSSE (FT2232, FT2232H, FT4232H and FT232H devices only)
0x4 = Synchronous Bit Bang (FT232R, FT245R,FT2232, FT2232H, FT4232H and FT232H devices only)
0x8 = MCU Host Bus Emulation Mode (FT2232, FT2232H, FT4232H and FT232H devices only)
0x10 = FastOpto-Isolated Serial Mode (FT2232, FT2232H, FT4232H and FT232H devices only)
0x20 = CBUS Bit Bang Mode (FT232Rand FT232H devices only)
0x40 = Single Channel Synchronous 245 FIFO Mode (FT2232H and FT232H devices only)
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetBitMode(handle, 0x0F, FT_MODE_ASYNC_BITBANG)
julia> FT_GetBitMode(handle)
0x01
See [`FT_GetBitMode`](@ref).
"""
function FT_SetBitMode(ftHandle::FT_HANDLE, ucMask, ucMode)
@assert ucMode in (FT_MODE_RESET,FT_MODE_ASYNC_BITBANG,FT_MODE_MPSSE,FT_MODE_SYNC_BITBANG,FT_MODE_MCU_EMULATION,FT_MODE_FAST_OPTO,FT_MODE_CBUS_BITBANG,FT_MODE_SCS_FIFO)
status = ccall((:FT_SetBitMode, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, UCHAR, UCHAR),
ftHandle, ucMask, ucMode)
check(status)
return
end
"""
FT_SetUSBParameters(ftHandle::FT_HANDLE, dwInTransferSize, dwOutTransferSize)
Set the USB request transfer size.
This function can be used to change the transfer sizes from the default transfer size
of 4096 bytes to better suit the application requirements. Transfer sizes must be set to a
multiple of 64 bytes between 64 bytes and 64k bytes. When FT_SetUSBParameters is called,
the change comes into effect immediately and any data that was held in the driver at the
time of the change is lost. Note that, at present, only dwInTransferSize is supported.
# Example
```julia-repl
julia> numdevs = FT_CreateDeviceInfoList()
0x00000004
julia> handle = FT_Open(0)
FT_HANDLE(Ptr{Nothing} @0x00000000051e56c0)
julia> FT_SetUSBParameters(handle, 16384, 8192)
"""
function FT_SetUSBParameters(ftHandle::FT_HANDLE, dwInTransferSize, dwOutTransferSize)
@assert 64 <= dwInTransferSize <= 65536
@assert 64 <= dwOutTransferSize <= 65536
status = ccall((:FT_SetUSBParameters, libftd2xx), cdecl, FT_STATUS,
(FT_HANDLE, DWORD, DWORD),
ftHandle, dwInTransferSize, dwOutTransferSize)
check(status)
return
end
end # module Wrapper
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 477 | # LibFTD2XX.jl
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
using LibFTD2XX
include("util.jl")
numdevs = LibFTD2XX.createdeviceinfolist()
if numdevs > 0
@info "found $numdevs devices. Running hardware tests..."
include("hardware/wrapper.jl")
include("hardware/LibFTD2XX.jl")
else
@info "found $numdevs devices. Running nohardware tests..."
include("nohardware/wrapper.jl")
include("nohardware/LibFTD2XX.jl")
end | LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 663 | # By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
module TestUtil
using Test
using LibFTD2XX.Util
@testset "util" begin
@test "hello" == ntuple2string(Cchar.(('h','e','l','l','o')))
@test "hello" == ntuple2string(Cchar.(('h','e','l','l','o','\0','x')))
@test v"0.0.0" == versionnumber(0)
@test v"99.99.99" == versionnumber(0x00999999)
@test v"2.12.28" == versionnumber(0x00021228)
@test_throws DomainError versionnumber(0x00999999 + 1)
@test_throws DomainError versionnumber(0x000000AA)
@test_throws DomainError versionnumber(0x0000AA00)
@test_throws DomainError versionnumber(0x00AA0000)
end
end | LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 10998 | # These tests require an FT device which supports D2XX to be connected
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
module TestLibFTD2XX
using Test
using LibFTD2XX
import LibFTD2XX.Wrapper
@testset "high level" begin
# libversion
if Sys.iswindows()
ver = libversion()
@test ver isa VersionNumber
else
@test_throws UndefVarError libversion()
end
# createdeviceinfolist
numdevs = LibFTD2XX.createdeviceinfolist()
@test numdevs > 0
# LibFTD2XX.getdeviceinfodetail
@test_throws D2XXException LibFTD2XX.getdeviceinfodetail(numdevs)
for deviceidx = 0:(numdevs-1)
idx, flgs, typ, devid, locid, serialn, descr, fthand = LibFTD2XX.getdeviceinfodetail(deviceidx)
@test idx == deviceidx
if Sys.iswindows() # should not have a locid on windows
@test locid == 0
end
@test serialn isa String
@test descr isa String
@test fthand isa FT_HANDLE
end
idx, flgs, typ, devid, locid, serialn, descr, fthand = LibFTD2XX.getdeviceinfodetail(0)
@test_throws DomainError LibFTD2XX.getdeviceinfodetail(-1)
# FT_HANDLE functions...
@testset "FT_HANDLE" begin
# open by description
if !isempty(descr)
handle = open(descr, OPEN_BY_DESCRIPTION)
@test handle isa FT_HANDLE
@test isopen(handle)
@test_throws Wrapper.FT_DEVICE_NOT_FOUND open(descr, OPEN_BY_DESCRIPTION) # can't open twice
close(handle)
@test !isopen(handle)
end
# open by serialnumber
if !isempty(serialn)
handle = open(serialn, OPEN_BY_SERIAL_NUMBER)
@test handle isa FT_HANDLE
@test isopen(handle)
@test_throws Wrapper.FT_DEVICE_NOT_FOUND open(serialn, OPEN_BY_SERIAL_NUMBER) # can't open twice
close(handle)
@test !isopen(handle)
end
# bytesavailable
handle = open(descr, OPEN_BY_DESCRIPTION)
nb = bytesavailable(handle)
@test nb >= 0
close(handle) # can't use on closed device
@test_throws D2XXException bytesavailable(handle)
# read
handle = open(descr, OPEN_BY_DESCRIPTION)
rxbuf = read(handle, nb)
@test length(rxbuf) == nb
@test_throws ArgumentError read(handle, -1) # exception type set by Base/io.jl
close(handle) # can't use on closed device
@test_throws D2XXException read(handle, nb)
# write
handle = open(descr, OPEN_BY_DESCRIPTION)
txbuf = ones(UInt8, 10)
nwr = write(handle, txbuf)
@test nwr == length(txbuf)
@test txbuf == ones(UInt8, 10)
@test_throws ErrorException write(handle, Int.(txbuf)) # No byte I/O...
close(handle) # can't use on closed device
@test_throws D2XXException read(handle, nb)
# readavailable
handle = open(descr, OPEN_BY_DESCRIPTION)
rxbuf = readavailable(handle)
@test rxbuf isa AbstractVector{UInt8}
close(handle) # can't use on closed device
@test_throws D2XXException readavailable(handle)
# baudrate
handle = open(descr, OPEN_BY_DESCRIPTION)
retval = baudrate(handle, 2000000)
@test retval == nothing
txbuf = ones(UInt8, 10)
nwr = write(handle, txbuf)
@test nwr == length(txbuf)
@test txbuf == ones(UInt8, 10)
@test_throws DomainError baudrate(handle, 0)
@test_throws DomainError baudrate(handle, -1)
close(handle) # can't use on closed device
@test_throws D2XXException baudrate(handle, 2000000)
# flush and eof
handle = open(descr, OPEN_BY_DESCRIPTION)
retval = flush(handle)
@test eof(handle)
@test retval == nothing
@test isopen(handle)
close(handle) # can't use on closed device
@test_throws D2XXException flush(handle)
@test_throws D2XXException eof(handle)
# driverversion
if Sys.iswindows()
handle = open(descr, OPEN_BY_DESCRIPTION)
ver = driverversion(handle)
@test ver isa VersionNumber
close(handle) # can't use on closed device
@test_throws D2XXException driverversion(handle)
else
handle = open(descr, OPEN_BY_DESCRIPTION)
@test_throws UndefVarError driverversion(handle)
close(handle) # can't use on closed device
end
# datacharacteristics
handle = open(descr, OPEN_BY_DESCRIPTION)
retval = datacharacteristics(handle, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
@test retval == nothing
close(handle) # can't use on closed device
@test_throws D2XXException datacharacteristics(handle, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
# timeouts tests...
handle = open(descr, OPEN_BY_DESCRIPTION)
baudrate(handle, 9600)
timeout_read, timeout_wr = 200, 100 # milliseconds
timeouts(handle, timeout_read, timeout_wr)
tread = 1000 * @elapsed read(handle, 5000)
buffer = zeros(UInt8, 5000);
twr = 1000 * @elapsed write(handle, buffer)
@test timeout_read < 1.5*tread
@test timeout_wr < 1.5*twr
@test_throws DomainError timeouts(handle, timeout_read, -1)
@test_throws DomainError timeouts(handle, -1, timeout_wr)
close(handle) # can't use on closed device
@test_throws D2XXException timeouts(handle, timeout_read, timeout_wr)
# status
handle = open(descr, OPEN_BY_DESCRIPTION)
mflaglist, lflaglist = status(handle)
@test mflaglist isa Dict{String, Bool}
@test lflaglist isa Dict{String, Bool}
@test haskey(mflaglist, "CTS")
@test haskey(mflaglist, "DSR")
@test haskey(mflaglist, "RI")
@test haskey(mflaglist, "DCD")
@test haskey(lflaglist, "OE")
@test haskey(lflaglist, "PE")
@test haskey(lflaglist, "FE")
@test haskey(lflaglist, "BI")
close(handle) # can't use on closed device
@test_throws D2XXException status(handle)
# close and isopen
handle = open(descr, OPEN_BY_DESCRIPTION)
retval = close(handle)
@test retval == nothing
@test !isopen(handle)
@test LibFTD2XX.Wrapper._ptr(handle) == C_NULL
retval = close(handle) # check can close more than once without issue...
@test !isopen(handle)
end
# D2XXDevice
@testset "D2XXDevice" begin
# Constructor
@test_throws DomainError D2XXDevice(-1)
for i = 0:(numdevs-1)
idx, flgs, typ, devid, locid, serialn, descr, fthand = LibFTD2XX.getdeviceinfodetail(i)
dev = D2XXDevice(i)
@test deviceidx(dev) == idx == i
@test deviceflags(dev) == flgs
@test devicetype(dev) == typ
@test deviceid(dev) == devid
if Sys.iswindows()
@test locationid(dev) == locid == 0
else
@test locationid(dev) == locid
end
@test serialnumber(dev) == serialn
@test description(dev) == descr
@test LibFTD2XX.Wrapper._ptr(fthandle(dev)) == LibFTD2XX.Wrapper._ptr(fthand)
@test !isopen(fthandle(dev))
end
# D2XXDevices
devices = D2XXDevices()
@test length(devices) == numdevs
@test all(deviceidx(devices[d]) == deviceidx(D2XXDevice(d-1)) for d = 1:numdevs)
# isopen
@test all(.!isopen.(devices))
# open
retval = open.(devices)
@test all(retval .== nothing)
@test all(isopen.(devices))
@test_throws D2XXException open.(devices) # can't open twice
# bytesavailable
nbs = bytesavailable.(devices)
@test all(nbs .>= 0)
close.(devices) # can't use on closed device
@test_throws D2XXException bytesavailable.(devices)
device = devices[1] # choose device 1...
nb = nbs[1]
# read
open(device)
rxbuf = read(device, nb)
@test length(rxbuf) == nb
@test_throws ArgumentError read(device, -1) # exception type set by Base/io.jl
close(device) # can't use on closed device
@test_throws D2XXException read(device, nb)
# write
open(device)
txbuf = ones(UInt8, 10)
nwr = write(device, txbuf)
@test nwr == length(txbuf)
@test txbuf == ones(UInt8, 10)
@test_throws ErrorException write(device, Int.(txbuf)) # No byte I/O...
close(device) # can't use on closed device
@test_throws D2XXException write(device, txbuf)
# readavailable
open(device)
rxbuf = readavailable(device)
@test rxbuf isa AbstractVector{UInt8}
close(device) # can't use on closed device
@test_throws D2XXException readavailable(device)
# baudrate
open(device)
retval = baudrate(device, 2000000)
@test retval == nothing
txbuf = ones(UInt8, 10)
nwr = write(device, txbuf)
@test nwr == length(txbuf)
@test txbuf == ones(UInt8, 10)
@test_throws DomainError baudrate(device, 0)
@test_throws DomainError baudrate(device, -1)
close(device) # can't use on closed device
@test_throws D2XXException baudrate(device, 2000000)
# flush and eof
open(device)
retval = flush(device)
@test eof(device)
@test retval == nothing
@test isopen(device)
close(device) # can't use on closed device
@test_throws D2XXException flush(device)
# driverversion
if Sys.iswindows()
open(device)
ver = driverversion(device)
@test ver isa VersionNumber
close(device) # can't use on closed device
@test_throws D2XXException driverversion(device)
else
@test_throws UndefVarError driverversion(device)
end
# datacharacteristics
open(device)
retval = datacharacteristics(device, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
@test retval == nothing
close(device) # can't use on closed device
@test_throws D2XXException datacharacteristics(device, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
# timeouts tests...
open(device)
baudrate(device, 9600)
timeout_read, timeout_wr = 200, 100 # milliseconds
timeouts(device, timeout_read, timeout_wr)
tread = 1000 * @elapsed read(device, 5000)
buffer = zeros(UInt8, 5000);
twr = 1000 * @elapsed write(device, buffer)
@test timeout_read < 1.5*tread
@test timeout_wr < 1.5*twr
@test_throws DomainError timeouts(device, timeout_read, -1)
@test_throws DomainError timeouts(device, -1, timeout_wr)
close(device) # can't use on closed device
@test_throws D2XXException timeouts(device, timeout_read, timeout_wr)
# status
open(device)
mflaglist, lflaglist = status(device)
@test mflaglist isa Dict{String, Bool}
@test lflaglist isa Dict{String, Bool}
@test haskey(mflaglist, "CTS")
@test haskey(mflaglist, "DSR")
@test haskey(mflaglist, "RI")
@test haskey(mflaglist, "DCD")
@test haskey(lflaglist, "OE")
@test haskey(lflaglist, "PE")
@test haskey(lflaglist, "FE")
@test haskey(lflaglist, "BI")
close(device) # can't use on closed device
@test_throws D2XXException status(device)
# close and isopen (all devices)
retval = close.(devices)
@test all(retval .== nothing)
@test all(.!isopen.(devices))
@test all(LibFTD2XX.Wrapper._ptr.(fthandle.(devices)) .== C_NULL)
close.(devices) # check can close more than once without issue...
@test all(.!isopen.(devices))
end
end
end # module TestLibFTD2XX
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 9954 | # These tests require an FT device which supports D2XX to be connected
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
module TestWrapper
using Test
using LibFTD2XX.Wrapper
using LibFTD2XX.Util
@testset "wrapper" begin
# FT_CreateDeviceInfoList tests...
numdevs = FT_CreateDeviceInfoList()
@test numdevs > 0
# FT_GetDeviceInfoList tests...
devinfolist, numdevs2 = FT_GetDeviceInfoList(numdevs)
@test numdevs2 == numdevs
@test length(devinfolist) == numdevs
description = ntuple2string(devinfolist[1].description)
if Sys.iswindows() # should not have a locid on windows
@test devinfolist[1].locid == 0
end
# FT_GetDeviceInfoDetail tests...
idx, flags, typ, id, locid, serialnumber, description, fthandle = FT_GetDeviceInfoDetail(0)
@test idx == 0
@test flags == devinfolist[1].flags
@test typ == devinfolist[1].typ
@test id == devinfolist[1].id
@test locid == devinfolist[1].locid
@test serialnumber == ntuple2string(devinfolist[1].serialnumber)
@test description == ntuple2string(devinfolist[1].description)
@test Wrapper._ptr(fthandle) == devinfolist[1].fthandle_ptr
# FT_ListDevices tests...
numdevs2 = Ref{UInt32}()
retval = FT_ListDevices(numdevs2, Ref{UInt32}(), FT_LIST_NUMBER_ONLY)
@test retval == nothing
@test numdevs2[] == numdevs
devidx = Ref{UInt32}(0)
buffer = pointer(Vector{Cchar}(undef, 64))
@test_throws ErrorException FT_ListDevices(devidx, buffer, FT_LIST_BY_INDEX|FT_OPEN_BY_SERIAL_NUMBER)
@test description != unsafe_string(buffer)
# FT_Open tests...
handle = FT_Open(0)
@test handle isa FT_HANDLE
@test Wrapper._ptr(handle) != C_NULL
FT_Close(handle)
# FT_OpenEx tests...
# by description
if !isempty(description)
handle = FT_OpenEx(description, FT_OPEN_BY_DESCRIPTION)
@test handle isa FT_HANDLE
@test Wrapper._ptr(handle) != C_NULL
FT_Close(handle)
end
# by serialnumber
if !isempty(serialnumber)
handle = FT_OpenEx(serialnumber, FT_OPEN_BY_SERIAL_NUMBER)
@test handle isa FT_HANDLE
@test Wrapper._ptr(handle) != C_NULL
FT_Close(handle)
end
# FT_Close tests...
handle = FT_Open(0)
retval = FT_Close(handle)
@test retval == nothing
@test_throws FT_STATUS_ENUM FT_Close(handle) # can't close twice...
# FT_Read tests...
handle = FT_Open(0)
buffer = zeros(UInt8, 5)
nread = FT_Read(handle, buffer, 0) # read 0 bytes
@test nread == 0
@test buffer == zeros(UInt8, 5)
@test_throws AssertionError FT_Read(handle, buffer, 6) # read 5 bytes
@test_throws AssertionError FT_Read(handle, buffer, -1) # read -1 bytes
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_Read(handle, buffer, 0)
# FT_Write tests...
handle = FT_Open(0)
buffer = ones(UInt8, 5)
nwr = FT_Write(handle, buffer, 0) # write 0 bytes
@test nwr == 0
@test buffer == ones(UInt8, 5)
nwr = FT_Write(handle, buffer, 2) # write 2 bytes
@test nwr == 2
@test buffer == ones(UInt8, 5)
@test_throws AssertionError FT_Write(handle, buffer, 6) # write 6 bytes
@test_throws AssertionError FT_Write(handle, buffer, -1) # write -1 bytes
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_Write(handle, buffer, 0)
# FT_SetDataCharacteristics tests...
handle = FT_Open(0)
retval = FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)
@test retval == nothing
# other combinations...
FT_SetDataCharacteristics(handle, FT_BITS_7, FT_STOP_BITS_1, FT_PARITY_NONE)
FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_2, FT_PARITY_NONE)
FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_EVEN)
FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_ODD)
FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_MARK)
FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_SPACE)
# Bad values
@test_throws AssertionError FT_SetDataCharacteristics(handle, ~(FT_BITS_8 | FT_BITS_7), FT_STOP_BITS_1, FT_PARITY_NONE)
@test_throws AssertionError FT_SetDataCharacteristics(handle, FT_BITS_8, ~(FT_STOP_BITS_1 | FT_STOP_BITS_2), FT_PARITY_NONE)
@test_throws AssertionError FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, ~(FT_PARITY_NONE | FT_PARITY_EVEN))
# closed handle
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)
# FT_SetTimeouts tests...
handle = FT_Open(0)
FT_SetBaudRate(handle, 9600)
timeout_read, timeout_wr = 200, 100 # milliseconds
FT_SetTimeouts(handle, timeout_read, timeout_wr)
buffer = zeros(UInt8, 5000);
tread = 1000 * @elapsed nread = FT_Read(handle, buffer, 5000)
twr = 1000 * @elapsed nwr = FT_Write(handle, buffer, 5000)
@test timeout_read < 1.5*tread
@test timeout_wr < 1.5*twr
@test_throws InexactError FT_SetTimeouts(handle, timeout_read, -1)
@test_throws InexactError FT_SetTimeouts(handle, -1, timeout_wr)
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetTimeouts(handle, timeout_read, timeout_wr)
# FT_GetModemStatus tests
handle = FT_Open(0)
flags = FT_GetModemStatus(handle)
@test flags isa DWORD
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_GetModemStatus(handle)
# FT_GetQueueStatus tests
handle = FT_Open(0)
nbrx = FT_GetQueueStatus(handle)
@test nbrx isa DWORD
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_GetQueueStatus(handle)
# FT_GetDeviceInfo tests
id_buf = id
serialnumber_buf = serialnumber
description_buf = description
handle = FT_Open(0)
typ, id, serialnumber, description = FT_GetDeviceInfo(handle)
@test typ isa FT_DEVICE
@test serialnumber == serialnumber_buf
@test description == description_buf
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_GetDeviceInfo(handle)
# FT_GetDriverVersion tests
if Sys.iswindows()
handle = FT_Open(0)
version = FT_GetDriverVersion(handle)
@test version isa DWORD
@test version > 0
@test (version >> 24) & 0xFF == 0x00 # 4th byte should be 0 according to docs
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_GetDriverVersion(handle)
else
handle = FT_Open(0)
@test_throws UndefVarError FT_GetDriverVersion(handle)
FT_Close(handle)
end
# FT_GetLibraryVersion tests
if Sys.iswindows()
version = FT_GetLibraryVersion()
@test version isa DWORD
@test version > 0
@test (version >> 24) & 0xFF == 0x00 # 4th byte should be 0 according to docs
else
@test_throws UndefVarError FT_GetLibraryVersion()
end
# FT_GetStatus tests
handle = FT_Open(0)
nbrx, nbtx, eventstatus = FT_GetStatus(handle)
@test nbrx isa DWORD
@test nbtx isa DWORD
@test eventstatus isa DWORD
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_GetStatus(handle)
# FT_SetBreakOn tests
handle = FT_Open(0)
retval = FT_SetBreakOn(handle)
@test retval == nothing
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetBreakOn(handle)
# FT_SetBreakOff tests
handle = FT_Open(0)
retval = FT_SetBreakOff(handle)
@test retval == nothing
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetBreakOff(handle)
# FT_Purge tests
handle = FT_Open(0)
retval = FT_Purge(handle, FT_PURGE_RX|FT_PURGE_TX)
@test retval == nothing
nbrx, nbtx, eventstatus = FT_GetStatus(handle)
nbrx_2 = FT_GetQueueStatus(handle)
@test nbrx == nbtx == nbrx_2 == 0
FT_Purge(handle, FT_PURGE_RX)
FT_Purge(handle, FT_PURGE_TX)
@test_throws AssertionError FT_Purge(handle, ~(FT_PURGE_RX))
@test_throws AssertionError FT_Purge(handle, ~(FT_PURGE_TX))
@test_throws AssertionError FT_Purge(handle, ~(FT_PURGE_RX | FT_PURGE_TX))
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_Purge(handle, FT_PURGE_RX|FT_PURGE_TX)
# FT_StopInTask and FT_RestartInTask tests
handle = FT_Open(0)
retval = FT_StopInTask(handle)
@test retval == nothing
nbrx, nbtx, eventstatus = FT_GetStatus(handle)
sleep(0.1)
nbrx_2, nbtx, eventstatus = FT_GetStatus(handle)
@test nbrx == nbrx_2
retval = FT_RestartInTask(handle)
@test retval == nothing
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_StopInTask(handle)
@test_throws FT_STATUS_ENUM FT_RestartInTask(handle)
# FT_FlowControl tests
handle = FT_Open(0)
@test_throws AssertionError FT_SetFlowControl(handle, 0xFF, 0x00, 0x01)
@test_throws InexactError FT_SetFlowControl(handle, FT_FLOW_NONE, 0x00, -1)
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetFlowControl(handle, FT_FLOW_NONE, 0x00, 0x00)
# FT_SetDtr, FT_ClrDtr, FT_SetRts and FT_ClrRts tests
handle = FT_Open(0)
retval = FT_SetDtr(handle)
@test retval == nothing
retval = FT_ClrDtr(handle)
@test retval == nothing
retval = FT_SetRts(handle)
@test retval == nothing
retval = FT_ClrRts(handle)
@test retval == nothing
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetDtr(handle)
@test_throws FT_STATUS_ENUM FT_ClrDtr(handle)
@test_throws FT_STATUS_ENUM FT_SetRts(handle)
@test_throws FT_STATUS_ENUM FT_ClrRts(handle)
# FT_EventNotification tests
# FT_SetChars tests
handle = FT_Open(0)
@test_throws InexactError FT_SetChars(handle, 0x00, 0x00, 0x00, -1)
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetChars(handle, 0x00, 0x00, 0x00, 0x00)
# FT_SetLatencyTimer and FT_GetLatencyTimer tests
handle = FT_Open(0)
FT_SetLatencyTimer(handle, 0xAC)
retval = FT_GetLatencyTimer(handle)
@test retval==0xAC
@test_throws InexactError FT_SetLatencyTimer(handle, 300)
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetLatencyTimer(handle, 128)
# FT_SetBitMode tests
handle = FT_Open(0)
@test_throws AssertionError FT_SetBitMode(handle, 0x00, 0xFF)
@test_throws InexactError FT_SetBitMode(handle, -1, FT_MODE_RESET)
FT_Close(handle)
@test_throws FT_STATUS_ENUM FT_SetBitMode(handle, 0x00, FT_MODE_RESET)
# FT_GetBitMode doesn't return the bit mode, but the pin status. So we can't check against that.
end
end # module TestWrapper
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 5195 | # These tests do not require an FT device which supports D2XX to be connected
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
module TestLibFTD2XX
using Test
using LibFTD2XX
import LibFTD2XX.Wrapper
@testset "high level" begin
# libversion
if Sys.iswindows()
ver = libversion()
@test ver isa VersionNumber
else
@test_throws UndefVarError libversion()
end
# createdeviceinfolist
numdevs = LibFTD2XX.createdeviceinfolist()
@test numdevs == 0
# LibFTD2XX.getdeviceinfodetail
@test_throws D2XXException LibFTD2XX.getdeviceinfodetail(0)
# FT_HANDLE functions...
@testset "FT_HANDLE" begin
# open by description
@test_throws Wrapper.FT_DEVICE_NOT_FOUND open("", OPEN_BY_DESCRIPTION)
# open by serialnumber
@test_throws Wrapper.FT_DEVICE_NOT_FOUND open("", OPEN_BY_SERIAL_NUMBER)
handle = FT_HANDLE() # create invalid handle...
# bytesavailable
@test_throws D2XXException bytesavailable(handle)
# read
@test_throws D2XXException read(handle, 0)
@test_throws D2XXException read(handle, 1)
if VERSION < v"1.3.0"
@test_throws ErrorException read(handle, -1) # exception type set by Base/io.jl
else
@test_throws ArgumentError read(handle, -1) # exception type set by Base/io.jl
end
# write
txbuf = ones(UInt8, 10)
@test_throws D2XXException write(handle, txbuf)
@test txbuf == ones(UInt8, 10)
@test_throws ErrorException write(handle, Int.(txbuf)) # No byte I/O...
# readavailable
@test_throws D2XXException readavailable(handle)
# baudrate
@test_throws D2XXException baudrate(handle, 9600)
@test_throws DomainError baudrate(handle, 0)
@test_throws DomainError baudrate(handle, -1)
# flush and eof
@test_throws D2XXException flush(handle)
@test_throws D2XXException eof(handle)
# driverversion
if Sys.iswindows()
@test_throws D2XXException driverversion(handle)
else
@test_throws UndefVarError driverversion(handle)
end
# datacharacteristics
@test_throws D2XXException datacharacteristics(handle, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
# timeouts tests...
timeout_read, timeout_wr = 200, 100 # milliseconds
@test_throws D2XXException timeouts(handle, timeout_read, timeout_wr)
@test_throws DomainError timeouts(handle, timeout_read, -1)
@test_throws DomainError timeouts(handle, -1, timeout_wr)
# status
@test_throws D2XXException status(handle)
# close and isopen
retval = close(handle)
@test retval == nothing
@test !isopen(handle)
@test LibFTD2XX.Wrapper._ptr(handle) == C_NULL
retval = close(handle) # check can close more than once without issue...
@test !isopen(handle)
end
# D2XXDevice
@testset "D2XXDevice" begin
# Constructor
@test_throws DomainError D2XXDevice(-1)
@test_throws D2XXException D2XXDevice(0)
# D2XXDevices
devices = D2XXDevices()
@test length(devices) == numdevs == 0
device = D2XXDevice(0, 0, 0, 0, 0, "", "", FT_HANDLE()) # blank device...
# isopen
@test !isopen(device)
# open
@test_throws Wrapper.FT_DEVICE_NOT_FOUND open(device)
# bytesavailable
@test_throws D2XXException bytesavailable(device)
nb = 1
# read
@test_throws D2XXException read(device, nb)
if VERSION < v"1.3.0"
@test_throws ErrorException read(device, -1) # exception type set by Base/io.jl
else
@test_throws ArgumentError read(device, -1) # exception type set by Base/io.jl
end
# write
txbuf = ones(UInt8, 10)
@test_throws D2XXException write(device, txbuf)
@test txbuf == ones(UInt8, 10)
@test_throws ErrorException write(device, Int.(txbuf)) # No byte I/O...
# readavailable
@test_throws D2XXException readavailable(device)
# baudrate
@test_throws D2XXException baudrate(device, 9600)
@test_throws DomainError baudrate(device, 0)
@test_throws DomainError baudrate(device, -1)
# flush and eof
@test_throws D2XXException flush(device)
@test_throws D2XXException eof(device)
# driverversion
if Sys.iswindows()
@test_throws D2XXException driverversion(device)
else
@test_throws UndefVarError driverversion(device)
end
# datacharacteristics
@test_throws D2XXException datacharacteristics(device, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
# timeouts tests...
timeout_read, timeout_wr = 200, 100 # milliseconds
@test_throws D2XXException timeouts(device, timeout_read, timeout_wr)
@test_throws DomainError timeouts(device, timeout_read, -1)
@test_throws DomainError timeouts(device, -1, timeout_wr)
# status
@test_throws D2XXException status(device)
# close and isopen (all devices)
retval = close.(devices)
@test all(retval .== nothing)
@test all(.!isopen.(devices))
@test all(LibFTD2XX.Wrapper._ptr.(fthandle.(devices)) .== C_NULL)
close.(devices) # check can close more than once without issue...
@test all(.!isopen.(devices))
end
end
end # module TestLibFTD2XX
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | code | 5744 | # These tests do not require an FT device which supports D2XX to be connected
#
# By Reuben Hill 2019, Gowerlabs Ltd, [email protected]
#
# Copyright (c) Gowerlabs Ltd.
module TestWrapper
using Test
using LibFTD2XX.Wrapper
using LibFTD2XX.Util
@testset "wrapper" begin
# FT_CreateDeviceInfoList tests...
numdevs = FT_CreateDeviceInfoList()
@test numdevs == 0
# FT_GetDeviceInfoList tests...
devinfolist, numdevs2 = FT_GetDeviceInfoList(numdevs)
@test numdevs2 == numdevs == 0
@test length(devinfolist) == numdevs == 0
# FT_GetDeviceInfoDetail tests...
@test_throws FT_STATUS_ENUM FT_GetDeviceInfoDetail(0)
# FT_ListDevices tests...
numdevs2 = Ref{UInt32}()
retval = FT_ListDevices(numdevs2, Ref{UInt32}(), FT_LIST_NUMBER_ONLY)
@test retval == nothing
@test numdevs2[] == numdevs
devidx = Ref{UInt32}(0)
buffer = pointer(Vector{Cchar}(undef, 64))
@test_throws ErrorException FT_ListDevices(devidx, buffer, FT_LIST_BY_INDEX|FT_OPEN_BY_SERIAL_NUMBER)
# FT_Open tests...
@test_throws FT_STATUS_ENUM FT_Open(0)
# FT_OpenEx tests...
# by description
@test_throws FT_STATUS_ENUM FT_OpenEx("", FT_OPEN_BY_DESCRIPTION)
# by serialnumber
@test_throws FT_STATUS_ENUM FT_OpenEx("", FT_OPEN_BY_SERIAL_NUMBER)
# FT_Close tests...
handle = FT_HANDLE() # create with invalid handle...
@test_throws FT_INVALID_HANDLE FT_Close(handle)
# FT_Read tests...
buffer = zeros(UInt8, 5)
@test_throws FT_INVALID_HANDLE FT_Read(handle, buffer, 0) # read 0 bytes
@test buffer == zeros(UInt8, 5)
@test_throws AssertionError FT_Read(handle, buffer, 6) # read 5 bytes
@test_throws AssertionError FT_Read(handle, buffer, -1) # read -1 bytes
# FT_Write tests...
buffer = ones(UInt8, 5)
@test_throws FT_INVALID_HANDLE FT_Write(handle, buffer, 0) # write 0 bytes
@test buffer == ones(UInt8, 5)
@test_throws AssertionError FT_Write(handle, buffer, 6) # write 6 bytes
@test_throws AssertionError FT_Write(handle, buffer, -1) # write -1 bytes
# FT_SetDataCharacteristics tests...
@test_throws FT_INVALID_HANDLE FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)
# Bad values
@test_throws AssertionError FT_SetDataCharacteristics(handle, ~(FT_BITS_8 | FT_BITS_7), FT_STOP_BITS_1, FT_PARITY_NONE)
@test_throws AssertionError FT_SetDataCharacteristics(handle, FT_BITS_8, ~(FT_STOP_BITS_1 | FT_STOP_BITS_2), FT_PARITY_NONE)
@test_throws AssertionError FT_SetDataCharacteristics(handle, FT_BITS_8, FT_STOP_BITS_1, ~(FT_PARITY_NONE | FT_PARITY_EVEN))
# closed handle
# FT_SetTimeouts tests...
timeout_read, timeout_wr = 200, 100 # milliseconds
@test_throws FT_INVALID_HANDLE FT_SetTimeouts(handle, timeout_read, timeout_wr)
@test_throws InexactError FT_SetTimeouts(handle, timeout_read, -1)
@test_throws InexactError FT_SetTimeouts(handle, -1, timeout_wr)
# FT_GetModemStatus tests
@test_throws FT_INVALID_HANDLE FT_GetModemStatus(handle)
# FT_GetQueueStatus tests
@test_throws FT_INVALID_HANDLE FT_GetQueueStatus(handle)
# FT_GetDeviceInfo tests
@test_throws FT_INVALID_HANDLE FT_GetDeviceInfo(handle)
# FT_GetDriverVersion tests
if Sys.iswindows()
@test_throws FT_INVALID_HANDLE FT_GetDriverVersion(handle)
else
@test_throws UndefVarError FT_GetDriverVersion(handle)
end
# FT_GetLibraryVersion tests
if Sys.iswindows()
version = FT_GetLibraryVersion()
@test version isa DWORD
@test version > 0
@test (version >> 24) & 0xFF == 0x00 # 4th byte should be 0 according to docs
else
@test_throws UndefVarError FT_GetLibraryVersion()
end
# FT_GetStatus tests
@test_throws FT_INVALID_HANDLE FT_GetStatus(handle)
# FT_SetBreakOn tests
@test_throws FT_INVALID_HANDLE FT_SetBreakOn(handle)
# FT_SetBreakOff tests
@test_throws FT_INVALID_HANDLE FT_SetBreakOff(handle)
# FT_Purge tests
@test_throws FT_INVALID_HANDLE FT_Purge(handle, FT_PURGE_RX|FT_PURGE_TX)
@test_throws AssertionError FT_Purge(handle, ~(FT_PURGE_RX))
@test_throws AssertionError FT_Purge(handle, ~(FT_PURGE_TX))
@test_throws AssertionError FT_Purge(handle, ~(FT_PURGE_RX | FT_PURGE_TX))
# FT_StopInTask and FT_RestartInTask tests
@test_throws FT_INVALID_HANDLE FT_StopInTask(handle)
@test_throws FT_INVALID_HANDLE FT_RestartInTask(handle)
# FT_SetFlowControl tests
@test_throws FT_INVALID_HANDLE FT_SetFlowControl(handle, FT_FLOW_NONE, 0x00, 0x01)
@test_throws AssertionError FT_SetFlowControl(handle, 0xFF, 0x00, 0x01)
@test_throws InexactError FT_SetFlowControl(handle, FT_FLOW_NONE, 0x00, -1)
# FT_SetDtr and FT_ClrDtr tests
@test_throws FT_INVALID_HANDLE FT_SetDtr(handle)
@test_throws FT_INVALID_HANDLE FT_ClrDtr(handle)
# FT_SetRts and FT_ClrRts tests
@test_throws FT_INVALID_HANDLE FT_SetRts(handle)
@test_throws FT_INVALID_HANDLE FT_SetRts(handle)
# FT_EventNotification tests
# FT_SetChars tests
@test_throws InexactError FT_SetChars(handle, 0x00, 0x00, 0x00, -1)
@test_throws FT_INVALID_HANDLE FT_SetChars(handle, 0x00, 0x00, 0x00, 0x00)
# FT_SetLatencyTimer and FT_GetLatencyTimer tests
@test_throws InexactError FT_SetLatencyTimer(handle, 300)
@test_throws FT_INVALID_HANDLE FT_SetLatencyTimer(handle, 0x00)
@test_throws FT_INVALID_HANDLE FT_GetLatencyTimer(handle)
# FT_SetBitMode and FT_GetBitMode tests
@test_throws AssertionError FT_SetBitMode(handle, 0x00, 0xFF)
@test_throws InexactError FT_SetBitMode(handle, -1, FT_MODE_RESET)
@test_throws FT_INVALID_HANDLE FT_SetBitMode(handle, 0x00, FT_MODE_RESET)
@test_throws FT_INVALID_HANDLE FT_GetBitMode(handle)
# FT_SetUSBParameters tests
@test_throws FT_INVALID_HANDLE FT_SetUSBParameters(handle, 32768, 32768)
end
end # module TestWrapper
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.4.0 | 5d154e25b3813c038711b0005617990ea28eb4bd | docs | 5617 | # LibFTD2XX
[](https://coveralls.io/github/Gowerlabs/LibFTD2XX.jl?branch=master)
[](https://codecov.io/gh/Gowerlabs/LibFTD2XX.jl)
[](https://travis-ci.org/Gowerlabs/LibFTD2XX.jl)
[](https://ci.appveyor.com/project/samuelpowell/libftd2xx-jl/branch/master)
Julia wrapper for the FTDIchip FTD2XX driver.
# Installation & Platforms
Install LibFTD2XX using the package manager:
```julia
]add LibFTD2XX
```
| Platform | Architecture | Notes |
| ------------- | ----------------------------- | --------------------------------------- |
| Linux (x86) | 32-bit and 64-bit | 64-bit tested locally ([No CI](https://github.com/Gowerlabs/LibFTD2XX.jl/issues/35)) |
| Linux (ARM) | ARMv7 HF and AArch64 (ARMv8) | Tested locally (No CI) |
| MacOS | 64-bit | CI active (without hardware) |
| Windows | 64-bit | CI active (without hardware) |
## Linux driver details
It is likely that the kernel will automatically load VCP drivers when running on linux, which will prevent the D2XX drivers from accessing the device. Follow the guidance in the FTDI Linux driver [README](https://www.ftdichip.com/Drivers/D2XX/Linux/ReadMe-linux.txt) to unload the `ftdio_sio` and `usbserial` kernel modules before use. These can optionally be blacklisted if appropriate. If your device has an alternate product name you may prefer to use an alternative approach detailed [here](https://www.elektormagazine.de/news/ftdi-d2xx-and-linux-overcoming-the-big-problem-).
The D2XX drivers use raw USB access through `libusb` which may not be available to non-root users. A udev file is required to enable access to a specified group. A script to create the appropriate file and user group is available, e.g., [here](https://stackoverflow.com/questions/13419691/accessing-a-usb-device-with-libusb-1-0-as-a-non-root-user).
# Usage
LibFTD2XX provides a high-level wrapper of the underlying library functionality, detailed below.
To access the library directly, the submodule `Wrapper` provides access to the functions detailed in the [D2XX Programmer's Guide (FT_000071)](http://www.ftdichip.com/Support/Documents/ProgramGuides/D2XX_Programmer's_Guide(FT_000071).pdf).
The demonstration considers a port running at 2MBaud which echos what it receives.
## Finding and configuring devices
```Julia
julia> using LibFTD2XX
julia> devices = D2XXDevices()
4-element Array{D2XXDevice,1}:
D2XXDevice(0, 2, 7, 67330065, 0, "FT3V1RFFA", "USB <-> Serial Converter A", Base.RefValue{FT_HANDLE}(FT_HANDLE(Ptr{Nothing} @0x0000000000000000)))
D2XXDevice(1, 2, 7, 67330065, 0, "FT3V1RFFB", "USB <-> Serial Converter B", Base.RefValue{FT_HANDLE}(FT_HANDLE(Ptr{Nothing} @0x0000000000000000)))
D2XXDevice(2, 2, 7, 67330065, 0, "FT3V1RFFC", "USB <-> Serial Converter C", Base.RefValue{FT_HANDLE}(FT_HANDLE(Ptr{Nothing} @0x0000000000000000)))
D2XXDevice(3, 2, 7, 67330065, 0, "FT3V1RFFD", "USB <-> Serial Converter D", Base.RefValue{FT_HANDLE}(FT_HANDLE(Ptr{Nothing} @0x0000000000000000)))
julia> isopen.(devices)
4-element BitArray{1}:
false
false
false
false
julia> device = devices[1]
D2XXDevice(0, 2, 7, 67330065, 0, "FT3V1RFFA", "USB <-> Serial Converter A", Base.RefValue{FT_HANDLE}(FT_HANDLE(Ptr{Nothing} @0x0000000000000000)))
julia> open(device)
julia> isopen(device)
true
julia> datacharacteristics(device, wordlength = BITS_8, stopbits = STOP_BITS_1, parity = PARITY_NONE)
julia> baudrate(device,2000000)
julia> timeout_read, timeout_wr = 200, 10; # milliseconds
julia> timeouts(device, timeout_read, timeout_wr)
```
## Basic IO
```julia
julia> supertype(typeof(device))
IO
julia> write(device, Vector{UInt8}(codeunits("Hello")))
0x00000005
julia> bytesavailable(device)
0x00000005
julia> String(read(device, 5)) # read 5 bytes
"Hello"
julia> write(device, Vector{UInt8}(codeunits("World")))
0x00000005
julia> String(readavailable(device)) # read all available bytes
"World"
julia> write(device, Vector{UInt8}(codeunits("I will be deleted.")))
0x00000012
julia> bytesavailable(device)
0x00000012
julia> flush(device)
julia> bytesavailable(device)
0x00000000
julia> # Read Timeout behaviour
julia> tread = 1000 * @elapsed read(device, 5000) # nothing to read! Will timeout...
203.20976900000002
julia> timeout_read < 1.5*tread # 1.5*tread to allow for extra compile/run time.
true
```
## Timeouts (only tested on Windows)
```
julia> buffer = zeros(UInt8, 5000);
julia> twr = 1000 * @elapsed nb = write(device, buffer) # Will timeout before finishing write!
22.997304
julia> timeout_wr < 1.5*twr
true
julia> nb # doesn't correctly report number written
0x00000000
julia> Int(bytesavailable(device))
3584
julia> timeout_wr < 1.5*twr
true
julia> flush(device)
julia> timeout_wr = 1000; # increase write timeout
julia> timeouts(device, timeout_read, timeout_wr)
julia> twr = 1000 * @elapsed nb = write(device, buffer) # Won't timeout before finishing write!
15.960230999999999
julia> nb # correctly reports number written
0x00001388
julia> Int(bytesavailable(device))
5000
julia> timeout_wr < 1.5*twr
false
julia> close(device)
julia> isopen(device)
false
```
| LibFTD2XX | https://github.com/Gowerlabs/LibFTD2XX.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 608 | using Bosonic
using Documenter
DocMeta.setdocmeta!(Bosonic, :DocTestSetup, :(using Bosonic); recursive=true)
makedocs(;
modules=[Bosonic],
authors="Marco Di Tullio",
repo="https://github.com/Marco-Di-Tullio/Bosonic.jl/blob/{commit}{path}#{line}",
sitename="Bosonic.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://Marco-Di-Tullio.github.io/Bosonic.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/Marco-Di-Tullio/Bosonic.jl",
devbranch="main",
)
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 278 | module Bosonic
using SparseArrays
using LinearAlgebra
include("operators_fixed.jl")
include("states_fixed.jl")
include("correlations.jl")
export basis_m, bdb, bbd, Op_fixed, dim, nume, le, basis, b, bd, state_form
export State_fixed, st, ope, nume, dim, basis, typ, rhosp
end
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 4348 |
function basis_m(n::Int64,m::Int64)
len = binomial(n+m-1,m)
base = spzeros(len,n)
counter = 1
index = Int64[]
for i in 1:((m+1)^n-1)
bin_vec = splitter(string(i,base=(m+1)),n)
if sum(bin_vec) == m
base[counter,:] = bin_vec
append!(index,i)
counter += 1
end
end
return base, index
end
function splitter(x,n)
vectorized = zeros(Int64,0)
while length(x) < n
x = "0"*x
end
for i in x
str_to_int = parse(Int, i)
append!(vectorized, str_to_int)
end
return vectorized
end
function myfind(c,j)
a = similar(c, Int)
count = 1
@inbounds for i in eachindex(c)
a[count] = i
count += (c[i] == j)
end
return a[1:(count-1)]
end
function bdb(n::Int64, m::Int64, i::Int64, j::Int64)
base, ind = basis_m(n,m)
l = binomial(n+m-1,m)
op = spzeros(l,l)
if i==j
for k in 1:l
if base[k,:][j] != 0
op[k,k] = base[k,:][j]
end
end
else
for k in 1:l
if base[k,:][j] != 0
ill = Int(ind[k]-(m+1)^(n-j)+(m+1)^(n-i))
ill2 = myfind(ind, ill)[1]
op[ill2,k] = 1
end
end
end
return op
end
function bbd(n::Int64, m::Int64, i::Int64, j::Int64)
return bdb(n, m, j, i)
end
function bdb(base::SparseMatrixCSC{Float64,Int64}, ind::Array{Int64,1}, m::Int64, i::Int64, j::Int64)
l = size(base)[1]
n = size(base)[2]
op = spzeros(l,l)
if i==j
for k in 1:l
if base[k,:][j] != 0
op[k,k] = base[k,:][j]
end
end
else
for k in 1:l
if base[k,:][j] != 0
ill = Int(ind[k]-(m+1)^(n-j)+(m+1)^(n-i))
ill2 = myfind(ind, ill)[1]
op[ill2,k] = 1
end
end
end
return op
end
function bbd(base::SparseMatrixCSC{Float64,Int64}, ind::Array{Int64,1}, m::Int64, i::Int64, j::Int64)
return bdb(base, ind, m, j, i)
end
struct Op_fixed
dim::Int
nume::Int
bdbtot::SparseMatrixCSC{Float64,Int64}
le::Int
basis::SparseMatrixCSC{Float64,Int64}
Op_fixed(dim,nume) = new(dim, nume, operators_fixed(dim,nume)...)
end
dim(o::Op_fixed) = o.dim
nume(o::Op_fixed) = o.nume
bdbtot(o::Op_fixed) = o.bdbtot
le(o::Op_fixed) = o.le
basis(o::Op_fixed) = o.basis
bdb(o::Op_fixed,i,j) = bdbtot(o)[(1+(i-1)*le(o)):i*le(o),(1+(j-1)*le(o)):j*le(o)]
bbd(o::Op_fixed,i,j) = bdb(o,j,i)
# Here we create the full matrix with all
# fixed particle operators definitions
function operators_fixed(n::Int,m::Int)
l1 = binomial(n+m-1,m)
l2 = n*l1
bas,ind = basis_m(n,m)
z = spzeros(l2,l2)
for i in 1:n
for j in i:n
if i==j
z[(1+(i-1)*l1):i*l1,(1+(j-1)*l1):j*l1] = 1/2*bdb(bas,ind, m, i,j)
else
z[(1+(i-1)*l1):i*l1,(1+(j-1)*l1):j*l1] = bdb(bas,ind, m, i,j)
end
end
end
op_general = z+z'
return op_general, l1, bas
end
function bd(n::Int64, m::Int64, i::Int64)
base1, ind1 = basis_m(n,m)
l2 = binomial(n+m-1,m)
base2, ind2 = basis_m(n,m+1)
l1 = binomial(n+m,m+1)
op = spzeros(l1,l2)
s2 = sparse([(m+2)^l for l in 0:(n-1)])
for k in 1:l2
j = myfind(ind2, (s2[end:-1:1]'*base1[k,:])+(m+2)^(n-i))[1]
op[j,k] = 1
end
if m==0
return op
end
return op
end
function b(n::Int64, m::Int64, i::Int64)
op = bd(n, m-1, i)
return op'
end
# This serves for applying several creations op
# at once. Modes will be a vector with the chosen
# modes
function bd(n::Int64, m::Int64, modes::Array{Int64,1})
l = length(modes)
op = bd(n,m,modes[1])
for k in 2:l
op = bd(n,m+k-1,modes[k])*op
end
return op
end
function b(n::Int64, m::Int64, modes::Array{Int64,1})
l = length(modes)
op = b(n,m,modes[1])
for k in 2:l
op = b(n,m-k+1,modes[k])*op
end
return op
end
function state_form(v::SparseMatrixCSC{Float64, Int64})
i, j, w = findnz(v)
l = size(v)[1]
return sparsevec(i,w,l)
end
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 789 | struct State_fixed{T<:AbstractVector}
st::T
ope::Op_fixed
State_fixed(st,ope) = length(st) != binomial(dim(ope)+nume(ope)-1,nume(ope)) ? error("lenght of vector does not match dimension") : new{typeof(st)}(st/sqrt(st'*st),ope)
end
st(s::State_fixed) = s.st
ope(s::State_fixed) = s.ope
nume(s::State_fixed) = nume(s.ope)
dim(s::State_fixed) = dim(s.ope)
basis(s::State_fixed) = basis(s.ope)
typ(s::State_fixed) = eltype(s.st)
function rhosp(sta::State_fixed, precis=15)
n = dim(sta)
num = nume(sta)
rhospv = spzeros(typ(sta),n,n)
estate = st(sta)
o = ope(sta)
for i in 1:n
for j in 1:n
rhospv[i,j] = round(estate'*bdb(o, i, j)*estate, digits = precis)
end
end
return rhospv
end
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 769 | using Bosonic
using Test
@testset "Bosonic.jl" begin
@test basis_m(4,2)[1][1,:][4] == 2
@test basis_m(4,3)[2][4] == 12
@test bdb(4,2,1,2)[7,4] == 1
@test bbd(4,3,2,2)[10,10] == 3
@test bdb(basis_m(4,2)[1],basis_m(4,2)[2],2,1,2)[9,6] == 1
@test bbd(basis_m(4,2)[1],basis_m(4,2)[2],2,1,2)[6,9] == 1
@test bdb(Op_fixed(4,2),1,2)[9,6] == 1
@test bbd(Op_fixed(4,2),1,2)[9,10] == 1
@test dim(Op_fixed(5,1)) == 5
@test nume(Op_fixed(4,3)) == 3
@test le(Op_fixed(4,3)) == binomial(4+3-1,3)
@test basis(Op_fixed(4,2))[2,4] == 1
@test bd(4,1,1)[8,2] == 1
@test b(4,2,1)[1,7] == 1
@test bd(4,1,[1,2])[15,2] == 1
@test b(4,3,[1,2])[1,14] == 1
@test state_form(bd(4,0,[1,3,2,3]))[22] == 1
end
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 281 | #SafeTestsets makes every test run in a separate enviromment
#so that errors can be found independently
using SafeTestsets
@safetestset "Operators fixed tests" begin include("operators_fixed_test.jl") end
@safetestset "States fixed tests" begin include("states_fixed_test.jl") end
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | code | 365 | using Bosonic
using Test
@testset "Bosonic.jl" begin
@test round(st(State_fixed(ones(10),Op_fixed(4,2)))'*st(State_fixed(ones(10),Op_fixed(4,2))),digits=4) == 1
@test nume(State_fixed(ones(10),Op_fixed(4,2))) == 2
@test basis(State_fixed(ones(10),Op_fixed(4,2)))[1,:][4] == 2
@test rhosp(State_fixed(ones(10),Op_fixed(4,2)))[3,1] == 0.4
end
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | docs | 2298 | # Bosonic
<!---[](https://Marco-Di-Tullio.github.io/Bosonic.jl/stable)
[](https://Marco-Di-Tullio.github.io/Bosonic.jl/dev)
[](https://github.com/Marco-Di-Tullio/Bosonic.jl/actions/workflows/CI.yml?query=branch%3Amain)-->
<!--[](https://travis-ci.com/Marco-Di-Tullio/Bosonic.jl)-->
[](https://ci.appveyor.com/project/Marco-Di-Tullio/Bosonic-jl)
[](https://codecov.io/gh/Marco-Di-Tullio/Bosonic.jl)
<!--[](https://coveralls.io/github/Marco-Di-Tullio/Bosonic.jl?branch=main)-->
Bosonic is a Julia toolkit for implementing bosonic simulations and exploring its quantum information properties.
Everything relating to bosons can be expressed in terms of annihilation and creation operators. The full Fock space is infinite-dimensional, so this package focuses on the fixed particle number subspace. It numerically constructs bosonic operators in this reduced system, which _the secret weapon_ of this library. Then you can define states in the corresponding base and calculate several properties.
Many interesting quantities can be obtained from states in Bosonic, such as one body matrices entropy, partially traced systems, m-bodies density matrices, one body entropies, majorization relations, average particle number and more.
## Installation
For installing this package, you must first access the pkg REPL (by typing ']' in your command line) and then execute
```add Bosonic```
The pkg manager will automatically download the package. Then you can initialize it by typing
```using Bosonic```
Alternatively, you can install the package from an editor/Jupyter notebook by typing
```import Pkg```
```Pkg.add("Bosonic")```
```using Bosonic```

| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.1.0 | 1810c9e306efc739cfd6fbf597301024ce583a8d | docs | 178 | ```@meta
CurrentModule = Bosonic
```
# Bosonic
Documentation for [Bosonic](https://github.com/Marco-Di-Tullio/Bosonic.jl).
```@index
```
```@autodocs
Modules = [Bosonic]
```
| Bosonic | https://github.com/Marco-Di-Tullio/Bosonic.jl.git |
|
[
"MIT"
] | 0.0.1 | f196bb8032090867283e585876984290060a9230 | code | 6598 | module Internals
using TOML
using ReadableRegex
using Pkg
using Base: UUID, SHA1
using Chain
import Pkg.Versions: VersionRange
import Pkg.Registry: VersionInfo
using DataFrames
using DataFrameMacros
using ShiftedArrays
using Term
using Scratch
download_cache = ""
function __init__()
global download_cache = @get_scratch!("downloaded_files")
end
# Downloads a resource, stores it within a scratchspace
function download_dataset(url)
fname = joinpath(download_cache, basename(url))
if !isfile(fname)
download(url, fname)
end
return fname
end
function download_registry()
if !("General" in readdir(download_cache))
read(`git clone https://github.com/JuliaRegistries/General.git $(joinpath(download_cache, "General"))`, String)
end
end
function crawl_general_registry()
if !("General" in readdir(download_cache))
download_registry()
end
deps_toml_regex = "General/" * exactly(1, LETTER) *
"/" * one_or_more(char_not_in("/")) *
"/Deps.toml"
dep_files = []
for (root, dirs, files) in walkdir("$download_cache/General")
for file in files
full_path = joinpath(root, file)
if match(deps_toml_regex, full_path) != nothing
push!(dep_files, full_path)
end
end
end
return dep_files
end
function parse_deps_toml(dep_path)
deps_data_toml= TOML.parsefile(dep_path)
# Borrowed from here: https://github.com/JuliaLang/Pkg.jl/blob/503f31f64bcda5a60f0b3676730b689ff1f91aa9/src/Registry/registry_instance.jl#L172
deps_data_toml = convert(Dict{String, Dict{String, String}}, deps_data_toml)
deps = Dict{VersionRange, Dict{String, UUID}}()
for (v, data) in deps_data_toml
vr = VersionRange(v)
d = Dict{String, UUID}(dep => UUID(uuid) for (dep, uuid) in data)
deps[vr] = d
end
return deps
end
function parse_vers_toml(dep_path)
# Borrowed from here: https://github.com/JuliaLang/Pkg.jl/blob/503f31f64bcda5a60f0b3676730b689ff1f91aa9/src/Registry/registry_instance.jl#L154
dep_path = dirname(dep_path) * "/Versions.toml"
d_v= TOML.parsefile(dep_path)
version_info = Dict{VersionNumber, VersionInfo}(VersionNumber(k) =>
VersionInfo(SHA1(v["git-tree-sha1"]::String), get(v, "yanked", false)::Bool) for (k, v) in d_v)
return version_info
end
pkg_name_from_path = x -> split(x, '/')[end-1]
function build_pkg_info(ver_dict, dep_dict)
pkg_info = []
for pkg in keys(ver_dict)
for ver in ver_dict[pkg]
for dep in dep_dict[pkg]
if ver[1] in dep[1]
push!(pkg_info, (pkg, ver[1], collect(keys(dep[2]))[1]))
end
end
end
end
pkg_info_df = DataFrame(pkg_info)
rename!(pkg_info_df, ["package", "version", "dependency"])
return pkg_info_df
end
function generate_pkg_analysis(pkg_info_df, deps_list)
pkg_analysis = @chain pkg_info_df begin
@groupby(:package, :version)
@combine(:dependencies = join(:dependency, ","))
@transform(:dependencies = split.(:dependencies, ","))
@sort(:package, :version)
@groupby(:package)
@transform(:dropped_dependencies = @c lag(:dependencies, 1))
@transform(:new_dependencies = @m sort(setdiff(:dependencies, :dropped_dependencies)))
@transform(:dropped_dependencies = @m sort(setdiff(:dropped_dependencies, :dependencies)))
@transform!(@subset((:new_dependencies == []) | (:new_dependencies === missing)), :new_dependencies = nothing)
@transform!(@subset((:dropped_dependencies == []) | (:dropped_dependencies === missing)), :dropped_dependencies = nothing)
@groupby(:new_dependencies, :dropped_dependencies)
@combine(:pkg_count = length(:package), :packages = join(:package, ","))
@sort(-:pkg_count)
# Block list of packages not to be shown in the analysis
@subset((:new_dependencies != nothing) &
(:dropped_dependencies != nothing) &
(:new_dependencies != ["Test"]) &
(!(:dropped_dependencies ∈ [["Test"], ["Pkg"]]))
)
@transform(:difflist = sort([:new_dependencies; :dropped_dependencies]))
end
dupes = pkg_analysis[!, :difflist] .∈ (pkg_analysis[nonunique(pkg_analysis, :difflist), :difflist], )
pkg_swaps = sort(unique(vcat(pkg_analysis[!, :new_dependencies]..., pkg_analysis[!, :dropped_dependencies]...)))
return pkg_swaps, pkg_analysis
end
function pull_pkg_links(dep_files)
pkg_toml_regex = "General/" * exactly(1, LETTER) *
"/" * one_or_more(char_not_in("/")) *
"/Package.toml"
pkg_files = []
for (root, dirs, files) in walkdir("$download_cache/General")
for file in files
full_path = joinpath(root, file)
if match(pkg_toml_regex, full_path) != nothing
push!(pkg_files, full_path)
end
end
end
pkg_files
end
function parse_pkg_toml(pkg_path)
# Borrowed from here: https://github.com/JuliaLang/Pkg.jl/blob/503f31f64bcda5a60f0b3676730b689ff1f91aa9/src/Registry/registry_instance.jl#L154
d_v = TOML.parsefile(pkg_path)
return d_v
end
function print_pkg_swap_output(pkg_files, sample_output)
df_pkg = @chain pkg_files begin
parse_pkg_toml.()
hcat
DataFrame(:auto)
@select(:pkg = :x1["name"], :repo = :x1["repo"])
end
if nrow(sample_output) == 0
println("✨✨ No package swaps found.")
return
end
println(
@bold("Suggested Package Swaps:")
)
println()
dep_out = ""
for r in eachrow(sample_output)
if dep_out != r[:dropped_dependencies][1]
if dep_out != ""
println()
end
end
dep_out = r[:dropped_dependencies][1]
dep_in = r[:new_dependencies][1]
dep_out_link = @chain df_pkg @subset(:pkg == dep_out) @select(:repo)
dep_out_link = nrow(dep_out_link) > 0 ? dep_out_link[!, 1][1] : ""
dep_in_link = @chain df_pkg @subset(:pkg == dep_in) @select(:repo)
dep_in_link = nrow(dep_in_link) > 0 ? dep_in_link[!, 1][1] : ""
dep_out_fmt = Term.creat_link(dep_out_link, String(dep_out))
dep_in_fmt = Term.creat_link(dep_in_link, String(dep_in))
println(
@italic(@red(dep_out_fmt)) * " ↗️ " * @bold(@green(dep_in_fmt)) * @bold(" ($(r[:pkg_count])) ")
)
end
end
end # Internals
| PkgSwaps | https://github.com/jeremiahpslewis/PkgSwaps.jl.git |
|
[
"MIT"
] | 0.0.1 | f196bb8032090867283e585876984290060a9230 | code | 1192 | module PkgSwaps
using TOML
using Pkg
using Chain
using DataFrames
using DataFrameMacros
using Scratch
include("Internals.jl")
function recommend(; project_toml_path = "Project.toml")
deps_data_toml = TOML.parsefile(project_toml_path)
deps_list = collect(keys(deps_data_toml["deps"]))
deps_list = [[i] for i in deps_list]
dep_files = Internals.crawl_general_registry()
dep_dict = Dict(zip(Internals.pkg_name_from_path.(dep_files), Internals.parse_deps_toml.(dep_files)))
ver_dict = Dict(zip(Internals.pkg_name_from_path.(dep_files), Internals.parse_vers_toml.(dep_files)))
# TODO: Handle multiple dependency case (where two packages swapped in or out)
pkg_info = Internals.build_pkg_info(ver_dict, dep_dict)
pkg_swaps, pkg_analysis = Internals.generate_pkg_analysis(pkg_info, deps_list)
sample_output = @chain pkg_analysis begin
@subset(
(:dropped_dependencies ∈ deps_list)
)
@subset(:pkg_count > 1)
@select(:dropped_dependencies, :new_dependencies, :pkg_count)
end
pkg_files = Internals.pull_pkg_links(dep_files)
Internals.print_pkg_swap_output(pkg_files, sample_output)
end
end
| PkgSwaps | https://github.com/jeremiahpslewis/PkgSwaps.jl.git |
|
[
"MIT"
] | 0.0.1 | f196bb8032090867283e585876984290060a9230 | code | 146 | using PkgSwaps
using Test
@testset "PkgSwaps.jl" begin
PkgSwaps.recommend(; project_toml_path=joinpath(@__DIR__, "../", "Project.toml"))
end
| PkgSwaps | https://github.com/jeremiahpslewis/PkgSwaps.jl.git |
|
[
"MIT"
] | 0.0.1 | f196bb8032090867283e585876984290060a9230 | docs | 914 | # PkgSwaps.jl
``PkgSwaps`` makes recommendations for switching out Julia packages you are using for 'superior' packages, where 'superior' is defined as other packages in the Julia package registry having made the same swap. For example, if package ``A`` depends on package ``B`` and then in a subsequent version drops package ``B`` and adds package ``C``, ``PkgSwaps`` records this as a choice for ``C`` over ``B``. If your environment currently has package ``B``, ``PkgSwaps`` will then suggest you consider using package ``C`` in place of package ``B``.
``PkgSwaps`` assumes that the ``General`` package registry accurately reflects the decisions of engaged package maintainers in their aim of developing the best packages possible. ``PkgSwaps`` takes advantage of these publicly available decisions in order to nudge use of 'Pareto optimal' dependency sets.
```julia
using PkgSwaps
PkgSwaps.recommend()
```
| PkgSwaps | https://github.com/jeremiahpslewis/PkgSwaps.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 169 | using PyCall, Conda
Conda.add_channel("conda-forge")
Conda.add("meshio")
Conda.add("scipy")
Conda.add("sympy")
cmd = `pip3 install meshio scipy sympy --user`
run(cmd)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4937 | using FluxRC, Test
# Kou's benchmark results
"""
r
[-0.81684757, 0.63369515, -0.81684757, -0.10810302, -0.78379396, -0.10810302]
s
[0.63369515, -0.81684757, -0.81684757, -0.78379396, -0.10810302, -0.10810302]
rf
[-0.77459667, 0., 0.77459667, 0.77459667, 0., -0.77459667, -1., -1., -1.]
sf
[-1., -1., -1., -0.77459667, 0., 0.77459667, 0.77459667, 0., -0.77459667]
V
[[ 0.70710678, 1.45054272, 1.39329302, 0. , 0. ,
-0.04593312],
[ 0.70710678, -0.72527136, 0.43019448, 1.25620684, -0.83406781,
1.03084378],
[ 0.70710678, -0.72527136, 0.43019448, -1.25620684, 0.83406781,
1.03084378],
[ 0.70710678, -0.67569095, 0.30868284, 0. , -0. ,
-1.08925616],
[ 0.70710678, 0.33784547, -0.70898933, -0.58516552, -0.88132995,
0.04853591],
[ 0.70710678, 0.33784547, -0.70898933, 0.58516552, 0.88132995,
0.04853591]]
correction_coeffs
[[ 0.3928371 0.62853936 0.3928371 0.55555556 0.88888889 0.55555556
0.3928371 0.62853936 0.3928371 ]
[-0.55555556 -0.88888889 -0.55555556 -0.52003383 0.62853936 1.30570803
0.923275 0.44444444 -0.36771945]
[ 0.68041382 1.08866211 0.68041382 0.21689446 -0.76980036 1.70760644
1.20746009 -0.54433105 0.15336754]
[-0.74535599 0. 0.74535599 1.20746009 1.08866211 0.15336754
-0.10844723 -0.76980036 -0.85380322]
[ 0.91287093 -0. -0.91287093 -0.64549722 2. 0.64549722
-0.45643546 -1.41421356 0.45643546]
[ 0.60858062 -1.21716124 0.60858062 1.6939963 0.86066297 0.02732963
0.01932497 0.60858062 1.19783627]]
phifj_solution
[[ 0.39198253 0.72780648 0.39198253 -0.13710719 0.42817214 4.66476318
3.29848568 0.30276343 -0.09694943]
[-0.09694943 0.30276343 3.29848568 4.66476318 0.42817214 -0.13710719
0.39198253 0.72780648 0.39198253]
[ 3.29848568 0.30276343 -0.09694943 0.55434701 1.02927379 0.55434701
-0.09694943 0.30276343 3.29848568]
[ 0.20029351 2.7069103 0.20029351 -1.03402506 -0.97126559 0.00792184
0.00560158 -0.68678848 -0.73116613]
[-0.73116613 -0.68678848 0.00560158 0.00792184 -0.97126559 -1.03402506
0.20029351 2.7069103 0.20029351]
[ 0.00560158 -0.68678848 -0.73116613 0.2832578 3.82814926 0.2832578
-0.73116613 -0.68678848 0.00560158]]
"""
py_V = [
0.70710678 1.45054272 1.39329302 0.0 0.0 -0.04593312
0.70710678 -0.72527136 0.43019448 1.25620684 -0.83406781 1.03084378
0.70710678 -0.72527136 0.43019448 -1.25620684 0.83406781 1.03084378
0.70710678 -0.67569095 0.30868284 0.0 -0.0 -1.08925616
0.70710678 0.33784547 -0.70898933 -0.58516552 -0.88132995 0.04853591
0.70710678 0.33784547 -0.70898933 0.58516552 0.88132995 0.04853591
]
py_Vf = [
0.70710678 -1.0 1.22474487 -1.34164079 1.64316767 1.09544512
0.70710678 -1.0 1.22474487 0.0 -0.0 -1.36930639
0.70710678 -1.0 1.22474487 1.34164079 -1.64316767 1.09544512
0.70710678 -0.661895 0.27606157 1.5368458 -0.82158384 2.15610529
0.70710678 0.5 -0.61237244 0.8660254 1.59099026 0.6846532
0.70710678 1.661895 2.17342817 0.19520501 0.82158384 0.03478494
0.70710678 1.661895 2.17342817 -0.19520501 -0.82158384 0.03478494
0.70710678 0.5 -0.61237244 -0.8660254 -1.59099026 0.6846532
0.70710678 -0.661895 0.27606157 -1.5368458 0.82158384 2.15610529
]
phifj_ref = [
0.39198253 0.72780648 0.39198253 -0.13710719 0.42817214 4.66476318 3.29848568 0.30276343 -0.09694943
-0.09694943 0.30276343 3.29848568 4.66476318 0.42817214 -0.13710719 0.39198253 0.72780648 0.39198253
3.29848568 0.30276343 -0.09694943 0.55434701 1.02927379 0.55434701 -0.09694943 0.30276343 3.29848568
0.20029351 2.7069103 0.20029351 -1.03402506 -0.97126559 0.00792184 0.00560158 -0.68678848 -0.73116613
-0.73116613 -0.68678848 0.00560158 0.00792184 -0.97126559 -1.03402506 0.20029351 2.7069103 0.20029351
0.00560158 -0.68678848 -0.73116613 0.2832578 3.82814926 0.2832578 -0.73116613 -0.68678848 0.00560158
]
# my workflow
N = deg = 2
Np = (N + 1) * (N + 2) ÷ 2
pl, wl = tri_quadrature(N)
V = vandermonde_matrix(N, pl[:, 1], pl[:, 2])
Vr, Vs = ∂vandermonde_matrix(N, pl[:, 1], pl[:, 2])
∂l = ∂lagrange(V, Vr, Vs)
ϕ = correction_field(N, V)
pf, wf = triface_quadrature(N)
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
# Vandermonde -> solution points
V1 = hcat(V[1, :], V[3, :], V[5, :], V[2, :], V[4, :], V[6, :]) |> permutedims
@test V1 ≈ py_V
# Vandermonde -> flux points
Vf = zeros(9, 6)
for i = 1:3, j = 1:3
Vf[(i-1)*3+j, :] .= ψf[i, j, :]
end
@test Vf ≈ py_Vf
# coefficients
ϕ1 = zeros(6, 9)
for i = 1:3, j = 1:3
ϕ1[:, (i-1)*3+j] .= ϕ[i, j, :]
end
ϕ2 = hcat(ϕ1[1, :], ϕ1[3, :], ϕ1[5, :], ϕ1[2, :], ϕ1[4, :], ϕ1[6, :]) |> permutedims
@test ϕ2 ≈ phifj_ref
# reproduce from python script
cd(@__DIR__)
include("python_phi.jl")
py_sigma, py_fi, py_figrad =
py"get_phifj_solution_grad_tri"(N, N + 1, 6, 3 * (N + 1), N + 1, py_V, py_Vf)
@test ϕ2 ≈ py_fi
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 5814 | using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, OffsetArrays
using ProgressMeter: @showprogress
using Plots
pyplot()
cd(@__DIR__)
begin
set = Setup(
"gas",
"cylinder",
"2d0f",
"hll",
"nothing",
1, # species
3, # order of accuracy
"positivity", # limiter
"euler",
0.1, # cfl
1.0, # time
)
ps0 = KitBase.CSpace2D(1.0, 6.0, 60, 0.0, π, 50, 0, 0)
deg = set.interpOrder - 1
ps = FRPSpace2D(ps0, deg)
vs = nothing
gas = Gas(
1e-6,
2.0, # Mach
1.0,
1.0, # K
5 / 3,
0.81,
1.0,
0.5,
)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
u0 = zeros(ps.nr, ps.nθ, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
ρ = max(exp(-10 * ((ps.xpg[i, j, k, l, 1])^2 + (ps.xpg[i, j, k, l, 2] - 3.0)^2)), 1e-2)
prim = [ρ, 0.0, 0.0, 1.0]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
n1 = [[0.0, 0.0] for i = 1:ps.nr+1, j = 1:ps.nθ]
for i = 1:ps.nr+1, j = 1:ps.nθ
angle = sum(ps.dθ[1, 1:j-1]) + 0.5 * ps.dθ[1, j]
n1[i, j] .= [cos(angle), sin(angle)]
end
n2 = [[0.0, 0.0] for i = 1:ps.nr, j = 1:ps.nθ+1]
for i = 1:ps.nr, j = 1:ps.nθ+1
angle = π / 2 + sum(ps.dθ[1, 1:j-1])
n2[i, j] .= [cos(angle), sin(angle)]
end
function dudt!(du, u, p, t)
du .= 0.0
J, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1) - 2
ny = size(u, 2) - 2
nsp = size(u, 3)
f = zeros(nx, ny, nsp, nsp, 4, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
f[i, j, k, l, m, :] .= inv(J[i, j][k, l]) * [fg[m], gg[m]]
end
end
u_face = zeros(nx, ny, 4, nsp, 4)
f_face = zeros(nx, ny, 4, nsp, 4, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
for i = 2:nx, j = 1:ny, k = 1:nsp
#=fw = @view fx_interaction[i, j, k, :]
uL = local_frame(u_face[i-1, j, 2, k, :], n1[i, j][1], n1[i, j][2])
uR = local_frame(u_face[i, j, 4, k, :], n1[i, j][1], n1[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n1[i, j][1], n1[i, j][2])=#
fx_interaction[i, j, k, :] .=
0.5 .* (f_face[i-1, j, 2, k, :, 1] .+ f_face[i, j, 4, k, :, 1]) .-
40dt .* (u_face[i, j, 4, k, :] - u_face[i-1, j, 2, k, :])
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
for i = 1:nx, j = 2:ny, k = 1:nsp
#=fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], n2[i, j][1], n2[i, j][2])
uR = local_frame(u_face[i, j, 1, k, :], n2[i, j][1], n2[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n2[i, j][1], n2[i, j][2])=#
fy_interaction[i, j, k, :] .=
0.5 .* (f_face[i, j-1, 3, k, :, 2] .+ f_face[i, j, 1, k, :, 2]) .-
40dt .* (u_face[i, j, 1, k, :] - u_face[i, j-1, 3, k, :])
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
for i = 2:nx-1, j = 2:ny-1, k = 1:nsp, l = 1:nsp, m = 1:4
#=fxL = (inv(ps.Ji[i, j][4, l]) * n1[i, j])[1] * fx_interaction[i, j, l, m]
fxR = (inv(ps.Ji[i, j][2, l]) * n1[i+1, j])[1] * fx_interaction[i+1, j, l, m]
fyL = (inv(ps.Ji[i, j][1, k]) * n2[i, j])[2] * fy_interaction[i, j, l, m]
fyR = (inv(ps.Ji[i, j][3, k]) * n2[i, j+1])[2] * fy_interaction[i, j+1, l, m]
du[i, j, k, l, m] =
-(
rhs1[i, j, k, l, m] + rhs2[i, j, k, l, m] +
(fxL - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fxR - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fyL - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fyR - f_face[i, j, 3, k, m, 2]) * dhr[l]
)=#
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(fx_interaction[i, j, l, m] - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fx_interaction[i+1, j, l, m] - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fy_interaction[i, j, k, m] - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fy_interaction[i, j+1, k, m] - f_face[i, j, 3, k, m, 2]) * dhr[l]
)
end
return nothing
end
tspan = (0.0, 1.0)
p = (ps.J, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.002
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Midpoint(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:50
step!(itg)
end
contourf(ps.x, ps.y, itg.u[:, :, 2, 2, 1], aspect_ratio = 1, legend = true)
sol = zeros(ps.nr, ps.nθ, 4)
for i = 1:ps.nr, j = 1:ps.nθ
sol[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
contourf(ps.x, ps.y, sol[:, :, 2], aspect_ratio = 1, legend = true)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 5644 | using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
pyplot()
cd(@__DIR__)
begin
set = Setup(
case = "cylinder",
space = "2d0f",
flux = "hll",
collision = "nothing",
interpOrder = 3,
limiter = "positivity",
boundary = "euler",
cfl = 0.1,
maxTime = 1.0,
)
ps = begin
ps0 = KitBase.CSpace2D(1.0, 6.0, 30, 0.0, π, 40, 0, 1)
deg = set.interpOrder - 1
FRPSpace2D(ps0, deg)
end
vs = nothing
gas = Gas(Kn = 1e-6, Ma = 1.2, K = 1.0)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
u0 = OffsetArray{Float64}(undef, 1:ps.nr, 0:ps.nθ+1, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
prim = [1.0, ks.gas.Ma, 0.0, 1.0]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
n1 = [[0.0, 0.0] for i = 1:ps.nr+1, j = 1:ps.nθ]
for i = 1:ps.nr+1, j = 1:ps.nθ
angle = sum(ps.dθ[1, 1:j-1]) + 0.5 * ps.dθ[1, j]
n1[i, j] .= [cos(angle), sin(angle)]
end
n2 = [[0.0, 0.0] for i = 1:ps.nr, j = 1:ps.nθ+1]
for i = 1:ps.nr, j = 1:ps.nθ+1
angle = π / 2 + sum(ps.dθ[1, 1:j-1])
n2[i, j] .= [cos(angle), sin(angle)]
end
function dudt!(du, u, p, t)
du .= 0.0
J, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1)
ny = size(u, 2) - 2
nsp = size(u, 3)
f = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, nsp, nsp, 4, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
f[i, j, k, l, m, :] .= inv(J[i, j][k, l]) * [fg[m], gg[m]]
end
end
u_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4)
f_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
for i = 2:nx, j = 1:ny, k = 1:nsp
fx_interaction[i, j, k, :] .=
0.5 .* (f_face[i-1, j, 2, k, :, 1] .+ f_face[i, j, 4, k, :, 1]) .-
dt .* (u_face[i, j, 4, k, :] - u_face[i-1, j, 2, k, :])
end
for j = 1:ny, k = 1:nsp
ul = local_frame(u_face[1, j, 4, k, :], n1[1, j][1], n1[1, j][2])
prim = conserve_prim(ul, γ)
pn = zeros(4)
pn[2] = -prim[2]
pn[3] = -prim[3]
pn[4] = 2.0 - prim[4]
tmp = (prim[4] - 1.0)
pn[1] = (1 - tmp) / (1 + tmp) * prim[1]
ub = global_frame(prim_conserve(pn, γ), n1[1, j][1], n1[1, j][2])
fg, gg = euler_flux(ub, γ)
fb = zeros(4)
for m = 1:4
fb[m] = (inv(ps.Ji[1, j][4, k])*[fg[m], gg[m]])[1]
end
fx_interaction[1, j, k, :] .=
0.5 .* (fb .+ f_face[1, j, 4, k, :, 1]) .- dt .* (u_face[1, j, 4, k, :] - ub)
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
for i = 1:nx, j = 1:ny+1, k = 1:nsp
fy_interaction[i, j, k, :] .=
0.5 .* (f_face[i, j-1, 3, k, :, 2] .+ f_face[i, j, 1, k, :, 2]) .-
dt .* (u_face[i, j, 1, k, :] - u_face[i, j-1, 3, k, :])
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
for i = 1:nx-1, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(fx_interaction[i, j, l, m] - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fx_interaction[i+1, j, l, m] - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fy_interaction[i, j, k, m] - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fy_interaction[i, j+1, k, m] - f_face[i, j, 3, k, m, 2]) * dhr[l]
)
end
return nothing
end
tspan = (0.0, 1.0)
p = (ps.J, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.0002
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Midpoint(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:50#nt
for i = 1:ps.nr, k = 1:ps.deg+1, l = 1:ps.deg+1
u1 = itg.u[i, 1, 4-k, 4-l, :]
ug1 = [u1[1], u1[2], -u1[3], u1[4]]
itg.u[i, 0, k, l, :] .= ug1
u2 = itg.u[i, ps.nθ, 4-k, 4-l, :]
ug2 = [u2[1], u2[2], -u2[3], u2[4]]
itg.u[i, ps.nθ+1, k, l, :] .= ug2
end
@inbounds for j = 1:ps.nθ÷2, k = 1:ps.deg+1, l = 1:ps.deg+1
itg.u[ps.nr, j, k, l, :] .= itg.u[ps.nr-1, j, k, l, :]
end
step!(itg)
end
sol = zeros(ps.nr, ps.nθ, 4)
for i = 1:ps.nr, j = 1:ps.nθ
sol[i, j, :] .= conserve_prim(itg.u[i, j, 1, 1, :], ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
contourf(
ps.x[1:ps.nr, 1:ps.nθ],
ps.y[1:ps.nr, 1:ps.nθ],
sol[:, :, 1],
aspect_ratio = 1,
legend = true,
)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 6541 | using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
pyplot()
cd(@__DIR__)
begin
set = Setup(
case = "cylinder",
space = "2d0f",
flux = "hll",
collision = "nothing",
interpOrder = 3,
limiter = "positivity",
boundary = "euler",
cfl = 0.1,
maxTime = 1.0,
)
ps = begin
ps0 = KitBase.CSpace2D(1.0, 6.0, 30, 0.0, π, 40, 0, 1)
deg = set.interpOrder - 1
FRPSpace2D(ps0, deg)
end
vs = nothing
gas = Gas(Kn = 1e-6, Ma = 0.5, K = 1.0)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
u0 = OffsetArray{Float64}(undef, 1:ps.nr, 0:ps.nθ+1, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
prim = [1.0, 1.0, 0.0, 1.0]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
n1 = [[0.0, 0.0] for i = 1:ps.nr+1, j = 1:ps.nθ]
for i = 1:ps.nr+1, j = 1:ps.nθ
angle = sum(ps.dθ[1, 1:j-1]) + 0.5 * ps.dθ[1, j]
n1[i, j] .= [cos(angle), sin(angle)]
end
n2 = [[0.0, 0.0] for i = 1:ps.nr, j = 1:ps.nθ+1]
for i = 1:ps.nr, j = 1:ps.nθ+1
angle = π / 2 + sum(ps.dθ[1, 1:j-1])
n2[i, j] .= [cos(angle), sin(angle)]
end
function dudt!(du, u, p, t)
du .= 0.0
iJ, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1)
ny = size(u, 2) - 2
nsp = size(u, 3)
f = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, nsp, nsp, 4, 2)
@inbounds for i in axes(f, 1)
for j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
#f[i, j, k, l, m, :] .= inv(J[i, j][k, l]) * [fg[m], gg[m]]
f[i, j, k, l, m, :] .= iJ[i, j][k, l] * [fg[m], gg[m]]
end
end
end
u_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4)
f_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4, 2)
@inbounds for i in axes(u_face, 1)
for j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
@inbounds for i = 2:nx
for j = 1:ny, k = 1:nsp
fw = @view fx_interaction[i, j, k, :]
uL = local_frame(u_face[i-1, j, 2, k, :], n1[i, j][1], n1[i, j][2])
uR = local_frame(u_face[i, j, 4, k, :], n1[i, j][1], n1[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n1[i, j][1], n1[i, j][2])
end
end
@inbounds for j = 1:ny
for k = 1:nsp
ul = local_frame(u_face[1, j, 4, k, :], n1[1, j][1], n1[1, j][2])
prim = conserve_prim(ul, γ)
pn = zeros(4)
pn[2] = -prim[2]
pn[3] = prim[3]
pn[4] = 2.0 - prim[4]
tmp = (prim[4] - 1.0)
pn[1] = (1 - tmp) / (1 + tmp) * prim[1]
ub = prim_conserve(pn, γ)
#ub = global_frame(prim_conserve(pn, γ), n1[1, j][1], n1[1, j][2])
fw = @view fx_interaction[1, j, k, :]
flux_hll!(fw, ub, Array(ul), γ, 1.0)
fw .= global_frame(fw, n1[1, j][1], n1[1, j][2])
end
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
@inbounds for i = 1:nx
for j = 1:ny+1, k = 1:nsp
fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], n2[i, j][1], n2[i, j][2])
uR = local_frame(u_face[i, j, 1, k, :], n2[i, j][1], n2[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n2[i, j][1], n2[i, j][2])
end
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
@inbounds for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
@inbounds for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
end
@inbounds @threads for i = 1:nx-1
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
fxL = (inv(ps.Ji[i, j][4, l])*n1[i, j])[1] * fx_interaction[i, j, l, m]
fxR = (inv(ps.Ji[i, j][2, l])*n1[i+1, j])[1] * fx_interaction[i+1, j, l, m]
fyL = (inv(ps.Ji[i, j][1, k])*n2[i, j])[2] * fy_interaction[i, j, l, m]
fyR = (inv(ps.Ji[i, j][3, k])*n2[i, j+1])[2] * fy_interaction[i, j+1, l, m]
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(fxL - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fxR - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fyL - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fyR - f_face[i, j, 3, k, m, 2]) * dhr[l]
)
end
end
return nothing
end
tspan = (0.0, 1.0)
p = (ps.iJ, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.0005
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:20#nt
@inbounds for i = 1:ps.nr, k = 1:ps.deg+1, l = 1:ps.deg+1
u1 = itg.u[i, 1, 4-k, 4-l, :]
ug1 = [u1[1], u1[2], -u1[3], u1[4]]
itg.u[i, 0, k, l, :] .= ug1
u2 = itg.u[i, ps.nθ, 4-k, 4-l, :]
ug2 = [u2[1], u2[2], -u2[3], u2[4]]
itg.u[i, ps.nθ+1, k, l, :] .= ug2
end
@inbounds for j = 1:ps.nθ÷2, k = 1:ps.deg+1, l = 1:ps.deg+1
itg.u[ps.nr, j, k, l, :] .= itg.u[ps.nr-1, j, k, l, :]
end
step!(itg)
end
sol = zeros(ps.nr, ps.nθ, 4)
for i = 1:ps.nr, j = 1:ps.nθ
sol[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
contourf(
ps.x[1:ps.nr, 1:ps.nθ],
ps.y[1:ps.nr, 1:ps.nθ],
sol[:, :, 3],
aspect_ratio = 1,
legend = true,
)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 6545 | """
As the cylinder flow blows up somehow,
here is the code which uses the split boundary under a lower Mach number.
The initial still gas is driven by the far-field flow.
"""
using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
pyplot()
cd(@__DIR__)
begin
set = Setup(
case = "cylinder",
space = "2d0f",
flux = "hll",
collision = "nothing",
interpOrder = 3,
limiter = "positivity",
boundary = "euler",
cfl = 0.1,
maxTime = 1.0,
)
ps = begin
ps0 = KitBase.CSpace2D(1.0, 6.0, 10, 0.0, π, 30, 0, 1)
deg = set.interpOrder - 1
FRPSpace2D(ps0, deg)
end
vs = nothing
gas = Gas(Kn = 1e-6, Ma = 0.5, K = 1.0)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
u0 = OffsetArray{Float64}(undef, 1:ps.nr, 0:ps.nθ+1, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
sos = sound_speed(1.0, ks.gas.γ)
prim = begin
if i == ps.nr
[1.0, ks.gas.Ma * sos, 0.0, 1.0]
else
[1.0, 0.0, 0.0, 1.0]
end
end
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
n1 = [[0.0, 0.0] for i = 1:ps.nr+1, j = 1:ps.nθ]
for i = 1:ps.nr+1, j = 1:ps.nθ
angle = sum(ps.dθ[1, 1:j-1]) + 0.5 * ps.dθ[1, j]
n1[i, j] .= [cos(angle), sin(angle)]
end
n2 = [[0.0, 0.0] for i = 1:ps.nr, j = 1:ps.nθ+1]
for i = 1:ps.nr, j = 1:ps.nθ+1
angle = π / 2 + sum(ps.dθ[1, 1:j-1])
n2[i, j] .= [cos(angle), sin(angle)]
end
function dudt!(du, u, p, t)
du .= 0.0
iJ, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1)
ny = size(u, 2) - 2
nsp = size(u, 3)
f = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, nsp, nsp, 4, 2)
@inbounds @threads for i in axes(f, 1)
for j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
f[i, j, k, l, m, :] .= iJ[i, j][k, l] * [fg[m], gg[m]]
end
end
end
u_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4)
f_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4, 2)
@inbounds @threads for i in axes(u_face, 1)
for j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
@inbounds @threads for i = 2:nx
for j = 1:ny, k = 1:nsp
fw = @view fx_interaction[i, j, k, :]
uL = local_frame(u_face[i-1, j, 2, k, :], n1[i, j][1], n1[i, j][2])
uR = local_frame(u_face[i, j, 4, k, :], n1[i, j][1], n1[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n1[i, j][1], n1[i, j][2])
end
end
@inbounds @threads for j = 1:ny
for k = 1:nsp
ul = local_frame(u_face[1, j, 4, k, :], n1[1, j][1], n1[1, j][2])
fw = @view fx_interaction[1, j, k, :]
flux_boundary_maxwell!(fw, [1.0, 0.0, 0.0, 1.0], ul, 1, γ, 1.0, 1.0, 1)
fw .= global_frame(fw, n1[1, j][1], n1[1, j][2])
end
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
@inbounds @threads for i = 1:nx
for j = 1:ny+1, k = 1:nsp
fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], n2[i, j][1], n2[i, j][2])
uR = local_frame(u_face[i, j, 1, k, :], n2[i, j][1], n2[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n2[i, j][1], n2[i, j][2])
end
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
@inbounds @threads for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
@inbounds @threads for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
end
@inbounds @threads for i = 2:nx-1
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
fxL = (inv(ps.Ji[i, j][4, l])*n1[i, j])[1] * fx_interaction[i, j, l, m]
fxR = (inv(ps.Ji[i, j][2, l])*n1[i+1, j])[1] * fx_interaction[i+1, j, l, m]
fyL = (inv(ps.Ji[i, j][1, k])*n2[i, j])[2] * fy_interaction[i, j, l, m]
fyR = (inv(ps.Ji[i, j][3, k])*n2[i, j+1])[2] * fy_interaction[i, j+1, l, m]
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(fxL - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fxR - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fyL - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fyR - f_face[i, j, 3, k, m, 2]) * dhr[l]
)
end
end
return nothing
end
tspan = (0.0, 1.0)
p = (ps.iJ, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.0005
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:20#nt
@inbounds for i = 1:ps.nr, k = 1:ps.deg+1, l = 1:ps.deg+1
u1 = itg.u[i, 1, 4-k, 4-l, :]
ug1 = [u1[1], u1[2], -u1[3], u1[4]]
itg.u[i, 0, k, l, :] .= ug1
u2 = itg.u[i, ps.nθ, 4-k, 4-l, :]
ug2 = [u2[1], u2[2], -u2[3], u2[4]]
itg.u[i, ps.nθ+1, k, l, :] .= ug2
end
@inbounds for j = 1:ps.nθ÷2, k = 1:ps.deg+1, l = 1:ps.deg+1
itg.u[ps.nr, j, k, l, :] .= itg.u[ps.nr-1, j, k, l, :]
end
step!(itg)
end
sol = zeros(ps.nr, ps.nθ, 4)
for i = 1:ps.nr, j = 1:ps.nθ
sol[i, j, :] .= conserve_prim(itg.u[i, j, 1, 1, :], ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
contourf(
ps.x[1:ps.nr-1, 1:ps.nθ],
ps.y[1:ps.nr-1, 1:ps.nθ],
sol[1:ps.nr-1, :, 2],
aspect_ratio = 1,
legend = true,
)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4295 | using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq
using ProgressMeter: @showprogress
using Plots
pyplot()
cd(@__DIR__)
begin
set = Setup(
"gas",
"cylinder",
"2d0f",
"hll",
"nothing",
1, # species
3, # order of accuracy
"positivity", # limiter
"euler",
0.1, # cfl
1.0, # time
)
ps0 = KitBase.CSpace2D(1.0, 6.0, 60, 0.0, π, 50)
deg = set.interpOrder - 1
ps = FRPSpace2D(ps0, deg)
vs = nothing
gas = Gas(
1e-6,
2.0, # Mach
1.0,
1.0, # K
5 / 3,
0.81,
1.0,
0.5,
)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
n1 = [[0.0, 0.0] for i = 1:ps.nr+1, j = 1:ps.nθ]
for i = 1:ps.nr+1, j = 1:ps.nθ
angle = sum(ps.dθ[1, 1:j-1]) + 0.5 * ps.dθ[1, j]
n1[i, j] .= [cos(angle), sin(angle)]
end
n2 = [[0.0, 0.0] for i = 1:ps.nr, j = 1:ps.nθ+1]
for i = 1:ps.nr, j = 1:ps.nθ+1
angle = π / 2 + sum(ps.dθ[1, 1:j-1])
n2[i, j] .= [cos(angle), sin(angle)]
end
u0 = zeros(ps.nr, ps.nθ, deg + 1, deg + 1)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
u0[i, j, k, l] =
max(exp(-3 * ((ps.xpg[i, j, k, l, 1] - 2)^2 + (ps.xpg[i, j, k, l, 2] - 2)^2)), 1e-2)
end
function dudt!(du, u, p, t)
J, ll, lr, dhl, dhr, lpdm, ax, ay = p
nx = size(u, 1)
ny = size(u, 2)
nsp = size(u, 3)
f = zeros(nx, ny, nsp, nsp, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = ax * u[i, j, k, l], ay * u[i, j, k, l]
f[i, j, k, l, :] .= inv(J[i, j][k, l]) * [fg, gg]
end
u_face = zeros(nx, ny, 4, nsp)
f_face = zeros(nx, ny, 4, nsp, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp
u_face[i, j, 1, l] = dot(u[i, j, l, :], ll)
u_face[i, j, 2, l] = dot(u[i, j, :, l], lr)
u_face[i, j, 3, l] = dot(u[i, j, l, :], lr)
u_face[i, j, 4, l] = dot(u[i, j, :, l], ll)
for n = 1:2
f_face[i, j, 1, l, n] = dot(f[i, j, l, :, n], ll)
f_face[i, j, 2, l, n] = dot(f[i, j, :, l, n], lr)
f_face[i, j, 3, l, n] = dot(f[i, j, l, :, n], lr)
f_face[i, j, 4, l, n] = dot(f[i, j, :, l, n], ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp)
for i = 2:nx, j = 1:ny, k = 1:nsp
au =
(f_face[i, j, 4, k, 1] - f_face[i-1, j, 2, k, 1]) /
(u_face[i, j, 4, k] - u_face[i-1, j, 2, k] + 1e-6)
fx_interaction[i, j, k] = (
0.5 * (f_face[i, j, 4, k, 1] + f_face[i-1, j, 2, k, 1]) -
0.5 * abs(au) * (u_face[i, j, 4, k] - u_face[i-1, j, 2, k])
)
end
fy_interaction = zeros(nx, ny + 1, nsp)
for i = 1:nx, j = 2:ny, k = 1:nsp
au =
(f_face[i, j, 1, k, 2] - f_face[i, j-1, 3, k, 2]) /
(u_face[i, j, 1, k] - u_face[i, j-1, 3, k] + 1e-6)
fy_interaction[i, j, k] = (
0.5 * (f_face[i, j, 1, k, 2] + f_face[i, j-1, 3, k, 2]) -
0.5 * abs(au) * (u_face[i, j, 1, k] - u_face[i, j-1, 3, k])
)
end
rhs1 = zeros(nx, ny, nsp, nsp)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp
rhs1[i, j, k, l] = dot(f[i, j, :, l, 1], lpdm[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp
rhs2[i, j, k, l] = dot(f[i, j, k, :, 2], lpdm[l, :])
end
for i = 2:nx-1, j = 2:ny-1, k = 1:nsp, l = 1:nsp
du[i, j, k, l] = -(
rhs1[i, j, k, l] +
rhs2[i, j, k, l] +
(fx_interaction[i, j, l] - f_face[i, j, 4, l, 1]) * dhl[k] +
(fx_interaction[i+1, j, l] - f_face[i, j, 2, l, 1]) * dhr[k] +
(fy_interaction[i, j, k] - f_face[i, j, 1, k, 2]) * dhl[l] +
(fy_interaction[i, j+1, k] - f_face[i, j, 3, k, 2]) * dhr[l]
)
end
return nothing
end
tspan = (0.0, 1.0)
a = [1.0, 1.0]
p = (ps.J, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, a[1], a[2])
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.01
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Tsit5(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:10#nt
step!(itg)
end
contourf(ps.x, ps.y, itg.u[:, :, 2, 2], aspect_ratio = 1, legend = true)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 3168 | nx = 30
ny = 40
nsp = 3
u = u0
f = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, nsp, nsp, 4, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], ks.gas.γ)
for m = 1:4
f[i, j, k, l, m, :] .= inv(ps.J[i, j][k, l]) * [fg[m], gg[m]]
end
end
u_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4)
f_face = OffsetArray{Float64}(undef, 1:nx, 0:ny+1, 4, nsp, 4, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ps.ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], ps.lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], ps.lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ps.ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ps.ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], ps.lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], ps.lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ps.ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
for i = 2:nx, j = 1:ny, k = 1:nsp
fx_interaction[i, j, k, :] .=
0.5 .* (f_face[i-1, j, 2, k, :, 1] .+ f_face[i, j, 4, k, :, 1]) .-
dt .* (u_face[i, j, 4, k, :] - u_face[i-1, j, 2, k, :])
end
for j = 1:ny, k = 1:nsp
ul = local_frame(u_face[1, j, 4, k, :], n1[1, j][1], n1[1, j][2])
prim = conserve_prim(ul, ks.gas.γ)
pn = zeros(4)
pn[2] = -prim[2]
pn[3] = -prim[3]
pn[4] = 2.0 - prim[4]
tmp = (prim[4] - 1.0)
pn[1] = (1 - tmp) / (1 + tmp) * prim[1]
ub = global_frame(prim_conserve(pn, ks.gas.γ), n1[1, j][1], n1[1, j][2])
fg, gg = euler_flux(ub, ks.gas.γ)
fb = zeros(4)
for m = 1:4
fb[m] = (inv(ps.Ji[1, j][4, k])*[fg[m], gg[m]])[1]
end
fx_interaction[1, j, k, :] .=
0.5 .* (fb .+ f_face[1, j, 4, k, :, 1]) .- dt .* (u_face[1, j, 4, k, :] - ub)
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
for i = 1:nx, j = 1:ny+1, k = 1:nsp
fy_interaction[i, j, k, :] .=
0.5 .* (f_face[i, j-1, 3, k, :, 2] .+ f_face[i, j, 1, k, :, 2]) .-
dt .* (u_face[i, j, 1, k, :] - u_face[i, j-1, 3, k, :])
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], ps.dl[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], ps.dl[l, :])
end
du = zero(u)
for i = 1:nx-1, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
du[i, j, k, l, m] = -(
#rhs1[i, j, k, l, m] +
#rhs2[i, j, k, l, m] +
(fx_interaction[i, j, l, m] - f_face[i, j, 4, l, m, 1]) * ps.dhl[k] +
(fx_interaction[i+1, j, l, m] - f_face[i, j, 2, l, m, 1]) * ps.dhr[k] #+
#(fy_interaction[i, j, k, m] - f_face[i, j, 1, k, m, 2]) * ps.dhl[l] +
#(fy_interaction[i, j+1, k, m] - f_face[i, j, 3, k, m, 2]) * ps.dhr[l]
)
end
rhs1[1, j, 2, 2, 1]
rhs2[1, j, 2, 2, 1]
fx_interaction[1, j, 1, 1] - f_face[1, j, 4, 1, 1, 1]
fx_interaction[2, j, 2, 1] - f_face[1, j, 2, 2, 1, 1]
ps.dhl[2]
ps.dhr[2]
du[1, j, 2, 2, 1]
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.